stubbing a function using jest

不羁的心 提交于 2019-12-03 14:56:56

问题


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]);

回答1:


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




回答2:


Jest provides jest.fn(), which has some basic mocking and stubbing functionality.

If you're experienced and comfortable with sinon you could still create Jest-based tests which use sinon test doubles. However you'll lose the convenience of built in Jest matchers such as expect(myStubFunction).toHaveBeenCalled().



来源:https://stackoverflow.com/questions/45259086/stubbing-a-function-using-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!