用 Jest 模拟 require 语句

新手上路,请多包涵

求和.js

 module.exports = function sum(a, b){
    return a + b;
};

事物.js

 var sum = require("./sum");

module.exports = class Thing {
    add(a, b){
        return sum(a, b);
    }
}

东西.test.js

 test('1 + 2 = 3', () => {
    //Arrange
    var Thing = require('./Thing');
    var thing = new Thing();

    //Act
    var result = thing.add(1, 2);

    //Assert
    expect(result).toBe(3);
});

test('sum mocked', () => {
    //Arrange
    jest.mock('./sum', () => {
        return jest.fn(() => 42);
    });

    var Thing = require('./Thing');
    var thing = new Thing();

    //Act
    var result = thing.add(1, 2);

    //Assert
    expect(result).toBe(42);
});

测试时如何模拟总和“需要”依赖项?我收到以下错误。

 sum mocked

    expect(received).toBe(expected)

    Expected value to be (using ===):
      42
    Received:
      3

有趣的是,如果我使用 .only 单独运行每个测试,它们都可以单独运行。

过去我曾使用 proxyquire 来做这样的事情,但我想尽可能避免使用它。

原文由 RoboKozo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 540
2 个回答

在测试中,我添加了

beforeEach(() =>  {
    jest.resetModules();
});

并且测试按预期通过了。

原文由 RoboKozo 发布,翻译遵循 CC BY-SA 3.0 许可协议

取自 Jest Docs。

 beforeEach(() => {
  jest.resetModules();
});

test('moduleName 1', () => {
  jest.doMock('../moduleName', () => {
    return jest.fn(() => 1);
  });
  const moduleName = require('../moduleName');
  expect(moduleName()).toEqual(1);
});

test('moduleName 2', () => {
  jest.doMock('../moduleName', () => {
    return jest.fn(() => 2);
  });
  const moduleName = require('../moduleName');
  expect(moduleName()).toEqual(2);
});

https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options

原文由 Ryan Vice 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题