我想测试 AJAX 方法(vanilla XHR),但找不到使用 Jest 框架的方法。我为 Jasmine 找到了 mock-ajax.js
。问题是我找不到安装它的方法。
是否有更好的方法在 Jest 中对 Ajax 函数进行单元测试?
原文由 Tomasz Kasperek 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想测试 AJAX 方法(vanilla XHR),但找不到使用 Jest 框架的方法。我为 Jasmine 找到了 mock-ajax.js
。问题是我找不到安装它的方法。
是否有更好的方法在 Jest 中对 Ajax 函数进行单元测试?
原文由 Tomasz Kasperek 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以在 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
});
原文由 Alexander Ivantsov 发布,翻译遵循 CC BY-SA 3.0 许可协议
13 回答13k 阅读
7 回答2.2k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.3k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读
jest api 发生了一些变化。这是我用的。它什么都不做,但足以渲染我的组件。
在测试文件中:
import '../../__mock__/xhr-mock.js'