In my Jest test, I am trying to call a mock server using ajax with XMLHttpRequest
:
import mock from "xhr-mock";
describe("ajax callbacks", function() {
beforeEach(function() {
mock.setup();
});
afterAll(function() {
mock.teardown();
});
it("gets called when done", function(done) {
mock.get("/get-url", {
status: 200,
body: '{ "key": "value" }'
});
const doneCallback = jest.fn();
const xhr = new XMLHttpRequest();
xhr.open("GET", "/get-url");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
doneCallback();
done();
}
}
xhr.send();
expect(doneCallback).toHaveBeenCalled();
});
});
It's failing because the AJAX call is asynchronous and the expectation is made before the callback is called.
Is there a way for Jest to wait until the callback is called before making the expectation?
Please keep in mind that I cannot change the request to synchronous or switch to a Promise-based API just for testing purposes. This simplified version of the test may differ from the actual code being tested, which contains different abstractions.