I want to test AJAX methods (vanilla XHR) and I can\'t find the way to do it with Jest framework. I found mock-ajax.js
for Jasmine, the problem
Here's a function that will create a XMLHttpRequest mock and install it into window
for you.
const mockXMLHttpRequest = () => {
const mock = {
open: jest.fn(),
addEventListener: jest.fn(),
setRequestHeader: jest.fn(),
send: jest.fn(),
getResponseHeader: jest.fn(),
upload: {
addEventListener: jest.fn(),
},
};
window.XMLHttpRequest = jest.fn(() => mock);
return mock;
};
Which you can then use in a test like so:
const mock = mockXMLHttpRequest();
// Get the upload progress callback
// This assumes you attach your listeners in a stable order
expect(mock.upload.addEventListener).toHaveBeenCalledTimes(1);
const [[, progress]] = mock.upload.addEventListener.mock.calls;
// Get the load callback
expect(mock.addEventListener).toHaveBeenCalledTimes(1);
const [[, load]] = mock.addEventListener.mock.calls;
expect(mock.open).toHaveBeenCalled();
expect(mock.send).toHaveBeenCalled();
// Fire a progress event
progress({ loaded: 12, total: 100 });
// ...
mock.status = 201;
mock.getResponseHeader.mockReturnValue('application/json');
mock.response = JSON.stringify({ id: 111 });
// Fire a load event
load();
// ...