使用 Jest 在函数内部模拟函数

时间:2021-06-10 08:26:53

标签: javascript node.js typescript unit-testing jestjs

我想模拟一个在另一个函数内部调用的函数,并控制它可以返回的内容或可能引发的错误。

main.ts

import function from './function';

const main = async() => {
  ...
  try {
    value = await function(arguments);
  } catch(error) {
    ...
  }
}

例如,对于这种愚蠢的情况,如果我想测试是否使用正确的参数调用了“函数”,并模拟其返回值。我还希望能够模拟该函数抛出的错误。

基本上我不希望我的测试进入这个函数,我只想模拟它并用返回值测试主函数的其余部分,并测试 catch 处理程序。

这是我想做的事情的基础:

main.test.ts

import main from './main';
import function from './function';

describe('Test main', () => {
  it('should call function with the right arguments', async() => {
    function = jest.fn(() => value);
    await main();
    expect(function).toHaveBeenLastCalledWith(arguments);
    // expect not to have thrown error
  });
  it('should handle the error of function', async() => {
    function = jest.fn().mockRejectedValue(new Error('error'));
    await main();
    expect(function).toHaveBeenLastCalledWith(arguments);
    // expect to have thrown error
  });
});

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您需要模拟模块。

像这样:

import function from './function';

jest.mock("./function")

it("some", () => {
   function.mockRejectedValue(new Error('error'));
   //do stuff
   expect(function).toHaveBeenLastCalledWith(arguments);
});