求和
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);
}
}
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);
});
如何在测试时模拟 sum 'require' 依赖?我收到以下错误。
sum mocked
expect(received).toBe(expected)
Expected value to be (using ===):
42
Received:
3
有趣的是,如果我使用 .only 单独运行每个测试,它们都可以独立运行。
过去我曾使用 proxyquire 来做这样的事情,但我想尽可能避免使用它。
最佳答案
在测试中,我添加了
beforeEach(() => {
jest.resetModules();
});
并且测试按预期通过。
关于javascript - 用 Jest 模拟 require 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42729384/