我想测试AJAX方法(vanilla XHR),我找不到这样做的方法 笑话 框架。我发现 mock-ajax.js
对于Jasmine,问题是我找不到安装它的方法。
是否有更好的单元测试Ajax函数的方法 笑话?
我想测试AJAX方法(vanilla XHR),我找不到这样做的方法 笑话 框架。我发现 mock-ajax.js
对于Jasmine,问题是我找不到安装它的方法。
是否有更好的单元测试Ajax函数的方法 笑话?
您可以在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
});
您可以在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
});
开玩笑api已经改变了一点。这就是我使用的。它没有做任何事情,但它足以渲染我的组件。
const xhrMockClass = () => ({
open : jest.fn(),
send : jest.fn(),
setRequestHeader: jest.fn()
})
window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass)
并在测试文件中:
import '../../__mock__/xhr-mock.js'