使用jest来存根功能

时间:2017-07-22 20:50:34

标签: unit-testing mocking jestjs sinon

有没有办法使用jest API存根函数? 我以前常常使用sinon存根,在那里我可以使用存根编写单元测试,用于从我测试的单元中发出的任何函数调用 - http://sinonjs.org/releases/v1.17.7/stubs/

例如 -

sinon.stub(jQuery, "ajax").yieldsTo("success", [1, 2, 3]);

4 个答案:

答案 0 :(得分:24)

使用jest,您应该使用jest.spyOn

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

您可以在codesandboxhttps://codesandbox.io/s/018x609krw?expanddevtools=1&module=%2Findex.test.js&view=editor

上试用实例

答案 1 :(得分:2)

Jest provides jest.fn(),它具有一些基本的模拟和存根功能。

如果您对sinon有经验和舒适,您仍然可以创建使用sinon测试双打的基于Jest的测试。但是,您将失去内置Jest匹配器的便利性,例如mkdir repos cd repos mkdir test.git cd test.git git init --bare cd hooks nano post-receive

答案 2 :(得分:2)

我能够使用mockReturnValue和jquery的$.Deferred完全替代jquery。这使我可以手动解决我的Ajax调用,然后其余功能将继续(并且.done().success()等的任何链接都将执行。

示例:

const deferred = new $.Deferred();
$.ajax = jest.fn().mockReturnValue(deferred);

myClass.executeAjaxFunction();

const return_val = 7;

deferred.resolve(return_val)

然后,如果我有类似

的功能
$.ajax({
    type: 'GET',
    url: '/myurl'
}).done((val) => {
    window.property = val;
});

以下测试将通过

it('should set my property correctly', () => {
    expect(window.property).toBe(7);
});

当然,如果您想存根非jquery函数,则可以跳过此答案的延后部分。我遇到了一个有关ajax的问题​​,并提出了此解决方案,以测试使用Jest完成ajax调用后执行动作的函数。

答案 3 :(得分:0)

做了以下两件事,让它对我有用。

  1. 添加 __esModule:true 为我解决了这个问题。

    jest.mock('module',()=>({ __esModule: true, default: jest.fn() }));

  2. 在描述之前移动模拟部分。 (就在导入之后。)

    //移动到describe之前 -> jest.mock(...); describe('', ...);

希望这对某人有所帮助。

相关问题