有没有办法使用 jest API 来存根函数?
我习惯于使用 sinon 存根,在这里我可以使用存根为来自我的测试单元的任何函数调用编写单元测试 -http://sinonjs.org/releases/v1.17.7/stubs/ http://sinonjs.org/releases/v1.17.7/stubs/
例如-
sinon.stub(jQuery, "ajax").yieldsTo("success", [1, 2, 3]);
With jest
你应该使用jest.spyOn https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname:
jest
.spyOn(jQuery, "ajax")
.mockImplementation(({ success }) => success([ 1, 2, 3 ]));
完整示例:
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);
您可以尝试现场示例codesandbox
:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)