1

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?

Andrea
  • 20,253
  • 23
  • 114
  • 183

2 Answers2

4

You can $.trim() (jQuery trim, since IE<9 doesn't have it natively) the result, like this:

equal($.trim(response), 'foo', 'Ajax calls work correctly');

Why is this happening? It's likely a formatting error, e.g. Unix vs Windows line endings that are creeping in there on you.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • I tried to change the line ending, but it still did not work. But $.trim does its job. How can I check what kind of space is appended at the end? – Andrea Nov 20 '10 at 10:38
  • Sorry, I was a bit too rash in my previous comment. I still have problems even changing the line ending. But trim seems to cut whatever space is appended at the end of the string. – Andrea Nov 20 '10 at 10:39
  • @Andrea - I'd open it in another editor that'll show all special characters, I personally use Notepad2, but there are lots out there, Notepad++ for example – Nick Craver Nov 20 '10 at 10:39
  • Thanks Nick, this helped me to test an ajax (from php echo) data return with : if($.trim(data)) – Valky Feb 25 '12 at 17:13
0

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.)

{ "Text":"foo" }

Then test like:

equal(response.Text, 'foo', 'Ajax calls work correctly');

You need to set the AJAX return type to json in the jQuery AJAX call.

Hogsmill
  • 1,574
  • 13
  • 21