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
This is how I did it.
test.js
const open = jest.fn();
const onload = jest.fn((x) => {/* */});
const onerror = jest.fn();
const send = jest.fn(function(){
this.onload()
})
const xhrMockClass = function () {
return {
open,
send,
onerror,
onload
};
};
global.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass);
// ...
test('Should make a request', () => {
// do stuff to make request
expect(send).toHaveBeenCalled()
expect(onload).toHaveBeenCalledWith(/* */)
expect(open).toHaveBeenCalledWith('GET', 'some/url', true)
})