使用 jest 存根函数 [英] stubbing a function using jest
本文介绍了使用 jest 存根函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法使用 jest API 存根函数?我习惯于使用 sinon 存根,在那里我可以用存根为来自我测试单元的任何函数调用编写单元测试 -http://sinonjs.org/releases/v1.17.7/stubs/>
例如-
sinon.stub(jQuery, "ajax").yieldsTo("success", [1, 2, 3]);
解决方案
使用 jest
你应该使用 jest.spyOn
:
开玩笑.spyOn(jQuery, "ajax").mockImplementation(({ success }) => success([ 1, 2, 3 ]));
完整示例:
const spy = jest.fn();const 有效载荷 = [1, 2, 3];笑话.spyOn(jQuery, "ajax").mockImplementation(({ success }) => success(payload));jQuery.ajax({url: "https://example.api",成功:数据=>间谍(数据)});期望(间谍).toHaveBeenCalledTimes(1);期望(间谍).toHaveBeenCalledWith(有效载荷);
您可以在 codesandbox
上尝试实时示例:https://codesandbox.io/s/018x609krw?expanddevtools=1&module=%2Findex.test.js&view=editor
is there a way to stub a function using jest API? I'm used to working with sinon stub, where I can write unit-tests with stubs for any function call coming out of my tested unit- http://sinonjs.org/releases/v1.17.7/stubs/
for example-
sinon.stub(jQuery, "ajax").yieldsTo("success", [1, 2, 3]);
解决方案
With jest
you should use jest.spyOn
:
jest
.spyOn(jQuery, "ajax")
.mockImplementation(({ success }) => success([ 1, 2, 3 ]));
Full example:
const spy = jest.fn();
const payload = [1, 2, 3];
jest
.spyOn(jQuery, "ajax")
.mockImplementation(({ success }) => success(payload));
jQuery.ajax({
url: "https://example.api",
success: data => spy(data)
});
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(payload);
You can try live example on codesandbox
: https://codesandbox.io/s/018x609krw?expanddevtools=1&module=%2Findex.test.js&view=editor
这篇关于使用 jest 存根函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文