【问题标题】:mock a specific function in a module模拟模块中的特定功能
【发布时间】:2020-09-08 12:43:54
【问题描述】:

我在一个文件中有两个函数

file1.ts:

const function1 = () => {
  return 123;
};
const function2 = () => {
  return function1() + 2;
};

export { function1, function2 };

我正在使用 jest 为函数 2 编写单元测试。但我无法模拟函数 1

我刚刚尝试使用jest.spyOn 模拟function1

import * as helperFunctions from 'file1';
describe('test function2 ', () => {
  let functionSpy: any;
  beforeAll(() => {
    functionSpy = jest.spyOn(helperFunctions, 'function1 ');
  });

  afterAll(() => {
    functionSpy.mockReset();
  });
  test('test', () => {
    functionSpy.mockReturnValue(1);
    expect(helperFunctions.function2()).toEqual(3);
  });
});

在我的测试中,function1 没有被模拟,它仍然调用实际的实现。 任何帮助表示赞赏。

【问题讨论】:

  • 无法部分模拟模块。当您不需要模拟另一个函数时,您应该考虑将模块分成两个或仅以某种方式组合您的测试
  • Jest mock inner function的可能重复
  • 不可能以当前编写代码的方式在function2 内模拟对function1 的调用...有关详细信息,请参阅my answer here

标签: javascript mocking jestjs


【解决方案1】:

解决办法如下:

index.ts:

const function1 = () => {
  return 123;
};
const function2 = () => {
  return exports.function1() + 2;
};

exports.function1 = function1;
exports.function2 = function2;

单元测试:

describe('test function2 ', () => {
  const helperFunctions = require('./');
  helperFunctions.function1 = jest.fn();
  test('test', () => {
    helperFunctions.function1.mockReturnValueOnce(1);
    expect(helperFunctions.function2()).toEqual(3);
  });
});

单元测试结果:

 PASS  src/stackoverflow/56354252/index.spec.ts
  test function2 
    ✓ test (8ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.696s, estimated 3s

你可以找到这个问题的更多细节:https://github.com/facebook/jest/issues/936#issuecomment-214939935

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多