用Jest模拟需要语句

Rob*_*ozo 10 javascript unit-testing jestjs

sum.js

module.exports = function sum(a, b){
    return a + b;
};
Run Code Online (Sandbox Code Playgroud)

Thing.js

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

module.exports = class Thing {
    add(a, b){
        return sum(a, b);
    }
}
Run Code Online (Sandbox Code Playgroud)

Thing.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);
});
Run Code Online (Sandbox Code Playgroud)

在测试时如何模拟总和'require'依赖?我收到以下错误.

sum mocked

    expect(received).toBe(expected)

    Expected value to be (using ===):
      42
    Received:
      3
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我单独运行每个测试,只有他们自己都可以正常工作.

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

Rob*_*ozo 11

在测试中,我补充道

beforeEach(() =>  {
    jest.resetModules();
});
Run Code Online (Sandbox Code Playgroud)

并且测试按预期通过.


Leo*_*eno 6

我有一种感觉,每个测试文件都可以进行模拟。不要问我为什么\xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf

\n\n

对我来说最有效的方法是设置这样的测试:

\n\n
// sum.test.js\n//Arrange\nconst sum = require('./sum');\n\ntest('1 + 2 = 3', () => {\n    //Act\n    const result = sum(1, 2);\n\n    //Assert\n    expect(result).toBe(3);\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

和:

\n\n
// Thing.test.js\n//Arrange\nconst Thing = require('./Thing');\n\n// jest.mock are hoisted so you can keep imports/require on top\nconst sumSpy = jest.fn(() => 42);\njest.mock('./sum', () => sumSpy);\n\ntest('Thing', () => {\n    const thing = new Thing();\n\n    //Act\n    const result = thing.add(1, 2);\n\n    //Assert\n    expect(sumSpy).toHaveBeenCalledTimes(1);\n    expect(result).toBe(42);\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

您甚至可以为每个测试提供不同的模拟实现,例如:

\n\n
sumSpy.mockImplementation(() => NaN);\n
Run Code Online (Sandbox Code Playgroud)\n


Rya*_*ice 6

取自 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);
});
Run Code Online (Sandbox Code Playgroud)

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