I am trying to use Qunit to test some code, but I have some problems with Ajax calls. I cannot even get them to test correctly with the simplest Ajax call using jQuery methods. The problems seems to be that a trailing space is appended to the textResponse, no matter what I do.
My initial code was something like
asyncTest('Ajax calls', function() {
expect(1);
$.get('ajax.txt', {}, function(response) {
equal(response, 'foo', 'Ajax calls work correctly');
});
setTimeout(function() {
start();
}, 600);
});
where ajax.txt
is a text file containing olny the characters foo
. This test fails, reporting
Ajax calls work correctly, expected: "foo" result: "foo ", diff:
"foo""foo "
I have then tried the following:
- I have tested against "foo " (including a trailing space)
- I have done
response.replace(' ', '')
before testing - I have varied the font encoding of the ajax.txt file
- I have tested it both in Firefox and Chrome, each time cleaning the cache
- I have manually tested for equality inside an alert, even with == comparison
but in no case I was able to get a match. For instance in the first variant I got the puzzling answer
Ajax calls work correctly, expected: "foo " result: "foo ", diff: "foo "
I am now going slightly mad. What could I have been possibly doing wrong?
You can
$.trim()
(jQuery trim, since IE<9 doesn't have it natively) the result, like this:Why is this happening? It's likely a formatting error, e.g. Unix vs Windows line endings that are creeping in there on you.
I had similar - yes, very possibly line endings; I had to remove "\r" and "\n" to be sure it was working. The other way to get what you exopect is to use JSON. Get the AJAX call to return (e.g.)
Then test like:
You need to set the AJAX return type to json in the jQuery AJAX call.