我有以下功能。
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);
}
我在用
开玩笑
用于单元测试。
我在某个地方读到,测试原始XMLHttpRequest是个坏主意。是真的吗?
所以,创建于
XHR testing in Jest
回答
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();
});
但是,我有以下错误。
XHR成功
期望(jest.fn()).toBeCalledWith(期望)
应使用以下函数调用模拟函数:
[“获取”,“
http://example.com
“,对]
但没人叫它。
我犯了一个愚蠢的错误,但是,我不知道。我在单元测试方面很差。
任何帮助都将不胜感激。