0

I am trying to test a function that makes an AJAX request to an API. The value that the function sends to the API and the API's response are as expected. However, Jasmine keeps giving me Error: Expected Function to be "*insert random string*". How can I run this test properly and without errors via browser standalone version of Jasmine?

This is the function I am trying to test:

function handleInput(data) {

    var dataToSend = data;

    var xhr = new XMLHttpRequest();
     xhr.open("POST", "http://test.app/controllers/handleinput.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onload = function () {
            console.log(this.responseText);
           return this.responseText;
        };
        xhr.send("input=" + dataToSend);
}

This is the specs script:

describe('ajax request', function () {

  var randomString = Math.random().toString(36).substring(7);

  beforeEach(function (done) {
        handleInput(randomString)
        done();
    });

  it('receives the same string that it sends', function (done) {
    expect(handleInput).toBe(randomString);
    done();
  });
});

All I am trying to do is to verify that the function handleInput sends a random string to the server and receives the same string as the response.

  • `expect(handleInput).toBe(randomString)` - `handleInput` is a *function*, not a value. You're trying to compare it to a value. What should this test actually be validating? `handleInput()` doesn't return anything. You'd need to somehow validate that the console was logged to, since that's all it does. (You could provide mocks to the function for `xhr` and `console` and test the interactions with those mocks. That'll be a pretty significant change to your code.) – David Mar 21 '17 at 18:40
  • @David `handleInput` is supposed to return the value of the `responseText` property when `xhr.onload` is ready. All I am trying to do is to make sure that the value the function sends to the server is the same value that is returned by the server. How could I do that? –  Mar 21 '17 at 18:44
  • In that case you're going about it incorrectly. The linked duplicate explains the problem you're facing, where you're trying to synchronuosly return a response from an asynchronous operation. – David Mar 21 '17 at 18:46
  • @David but isn't that what the beforeEach method is for and why done() is invoked? –  Mar 21 '17 at 18:49

0 Answers0