I have following function.
export function sendWeatherrequest(countryName) {
let xmrRequest = new XMLHttpRequest();
xmrRequest.onload = requestListener;
xmrRequest.onerror = requestError;
xmrRequest.open('get', generateUrl(name), true);
xmrRequest.send();
}
function requestListener() {
let data = JSON.parse(this.responseText);
displayPage(data);
}
I am using jest for unit test.
As, i read somewhere that it is bad idea to test original XMLHttpRequest. Is it true?
So, created following from XHR testing in Jest answer
let open, send, status, onload, setRequestHeader, response;
function createXHRmock() {
open = jest.fn();
status = 200;
response = JSON.stringify([{
title: 'some data.',
weather: 'wind'
}]);
send = jest.fn().mockImplementation(function(){
onload = this.onload.bind(this);
onerror = this.onerror.bind(this);
});
const xhrMockClass = function () {
return {
open,
send,
status,
setRequestHeader,
response
};
};
window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass);
}
it('XHR success', () => {
createXHRmock();
expect(open).toBeCalledWith('GET', 'http://example.com', true);
expect(send).toBeCalled();
onload();
});
But, i am getting following error.
XHR success
expect(jest.fn()).toBeCalledWith(expected)
Expected mock function to have been called with: ["GET", "http://example.com", true] But it was not called.
My be i done some stupid mistake but, can't figureout. I am very poor in unit testing.
Any help would be greatly appreciated.
openonly gets called insendWeatherrequestbutsendWeatherrequestis never called in your test - Brian Adams