Bạn có thể kiểm tra XHR trong Jest mà không cần gói bổ sung. Đây là chức năng helper mà tạo ra đối tượng giả cho 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);
}
Và bạn có thể sử dụng nó trong thử nghiệm như sau:
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
});
Nguồn
2015-11-04 17:02:16
Tôi nghĩ rằng đây tại là 'jest.fn() mockImplementation' từ [tài liệu] (https://facebook.github.io /jest/docs/en/mock-function-api.html#mockfnmockimplementationfn) – Peter