我想测试AJAX方法(vanilla XHR),我找不到使用 Jest 框架的方法。我找到了Jasmine的mock-ajax.js
,问题是我找不到安装它的方法。
是否有更好的方法可以在 Jest 中对单元测试Ajax函数进行测试?
答案 0 :(得分:15)
开玩笑api已经改变了一点。这就是我使用的。它没有做任何事情,只有它足以渲染我的组件。
const xhrMockClass = () => ({
open : jest.fn(),
send : jest.fn(),
setRequestHeader: jest.fn()
})
window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass)
并在测试文件中:
import '../../__mock__/xhr-mock.js'
答案 1 :(得分:13)
您可以在没有其他包的情况下在Jest中测试XHR。这是辅助函数,它为XMLHttpRequest创建模拟对象:
let open, send, onload, onerror;
function createXHRmock() {
open = jest.genMockFn();
// be aware we use *function* because we need to get *this*
// from *new XmlHttpRequest()* call
send = jest.genMockFn().mockImpl(function(){
onload = this.onload.bind(this);
onerror = this.onerror.bind(this);
});
const xhrMockClass = function () {
return {
open,
send
};
};
window.XMLHttpRequest = jest.genMockFn().mockImpl(xhrMockClass);
}
您可以按如下方式在测试中使用它:
it('XHR success', () => {
createXHRmock();
// here you should call GET request
expect(open).toBeCalledWith('GET', 'http://example.com', true);
expect(send).toBeCalled();
// call onload or onerror
onload();
// here you can make your assertions after onload
});
答案 2 :(得分:1)
如前所述,您不需要其他库:
function test(username, password, role) {
const args = {
variables: {
where: {id: "someValue"},
data: {
username: username || undefined,
password: password || undefined,
role: role || undefined,
},
},
};
return JSON.stringify(args);
}
let json = test();
console.log(json);
文件obj = {}
data = {
"user1": {
"rights": 1,
"players": {
"1": "Ronaldo"
}
},
"user2": {
"rights": 1,
"players": {
"2": "Messi"
}
}
}
for user in data.keys():
obj[user] = data[user]
包含以下模拟:
// mocks.js is file where you could put your mocks (example below)
const mocks = require('./mocks.js')
test('XHR test', () => {
let xhrMock = {
open: jest.fn(),
setRequestHeader: jest.fn(),
onreadystatechange: jest.fn(),
send: jest.fn(),
readyState: 4,
responseText: JSON.stringify(mocks),
status: 200
}
window.XMLHttpRequest = jest.fn(() => xhrMock)
xhrMock.onreadystatechange()
sendData().then((response) => {
// You could do you checks here. Some examples:
expect(xhrMock.setRequestHeader).toBeCalledWith('Cache-Control', 'no-cache')
expect(xhrMock.open).toBeCalledWith('POST', 'you_api_url.com/end_point/')
expect(xhrMock.withCredentials).toBe(false)
let formData = new FormData()
formData.append('firstParam', 'firstParamValue')
expect(yoloRequestMock.send).toBeCalledWith(formData)
expect(JSON.stringify(response)).toBe(JSON.stringify(mocks))
})
// the following function is the one which sends the request (to be tested)
function sendData() {
return new Promise(function(resolve, reject) {
let formData = new FormData()
formData.append('firstParam', 'firstParamValue')
let xhr = new XMLHttpRequest()
xhr.withCredentials = false
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if(xhr.status === 200) {
resolve(JSON.parse(xhr.responseText))
} else {
reject(xhr.responseText)
}
}
}
xhr.open('POST', T2S_VISUAL_SEARCH_PARAMS.t2sVisualSeacchApiUrl)
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.send(formData)
})
}
}
答案 3 :(得分:1)
这是一个与Jest 26一起使用的TypeScript示例:
function performRequest(callback: any) {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/');
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4 || xhr.status !== 200) return;
callback(xhr.response);
};
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send(null);
}
describe('request', () => {
const xhrMock: Partial<XMLHttpRequest> = {
open: jest.fn(),
send: jest.fn(),
setRequestHeader: jest.fn(),
readyState: 4,
status: 200,
response: 'Hello World!'
};
jest.spyOn(window, 'XMLHttpRequest').mockImplementation(() => xhrMock as XMLHttpRequest);
const callback = jest.fn();
performRequest(callback);
expect(xhrMock.open).toBeCalledWith('GET', 'https://example.com/');
expect(xhrMock.setRequestHeader).toBeCalledWith('Accept', 'application/json');
(xhrMock.onreadystatechange as EventListener)(new Event(''));
expect(callback.mock.calls).toEqual([['Hello World!']]);
});
答案 4 :(得分:0)
这是一个将创建XMLHttpRequest模拟并将其安装到window
中的函数。
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;
};
然后您可以在像这样的测试中使用它:
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();
// ...
答案 5 :(得分:0)
这就是我的方法。
test.js
const open = jest.fn();
const onload = jest.fn((x) => {/* <your response data> */});
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(/* <your response data> */)
expect(open).toHaveBeenCalledWith('GET', 'some/url', true)
})