I have the following Jest test which includes calling 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();
});
});
which will obviously fail because the AJAX call is handled asynchronously and the expectation is made before the callback is called.
Is there any way where Jest can wait till the callback is called before making the expectation?
Please note that I cannot turn the request into a synchronous one because of the domain requirements. And neither can I turn it into a Promise based API just to be able to test it. This is just a simplified version of the test which is being written so that the folks here can grasp it easily. The actual code is different and it has abstractions to what is written here.
Aucun commentaire:
Enregistrer un commentaire