[英]Mocking require statements with Jest
sum.js sum.js
module.exports = function sum(a, b){
return a + b;
};
Thing.js Thing.js
var sum = require("./sum");
module.exports = class Thing {
add(a, b){
return sum(a, b);
}
}
Thing.test.js 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);
});
How can I mock the sum 'require' dependency when testing? 在测试时如何模拟总和'require'依赖? I get the following error.
我收到以下错误。
sum mocked
expect(received).toBe(expected)
Expected value to be (using ===):
42
Received:
3
What's interesting if I run each test individually with .only, they both work just fine on their own. 有趣的是,如果我单独运行每个测试,只有他们自己都可以正常工作。
In the past I've used proxyquire to do things like this but I'd like to avoid it if possible. 在过去,我曾使用proxyquire做这样的事情但我想尽可能避免它。
In the test, I added 在测试中,我补充道
beforeEach(() => {
jest.resetModules();
});
and the tests passed as expected. 并且测试按预期通过。
I have the feeling that mocking works per test file. 我觉得每个测试文件的模拟工作。 Don't ask me why ¯\\_(ツ)_/¯
不要问我为什么¯\\ _(ツ)_ /¯
The approach that worked the best for me was to set the tests like this: 对我来说最好的方法是设置这样的测试:
// sum.test.js
//Arrange
const sum = require('./sum');
test('1 + 2 = 3', () => {
//Act
const result = sum(1, 2);
//Assert
expect(result).toBe(3);
});
And: 和:
// Thing.test.js
//Arrange
const Thing = require('./Thing');
// jest.mock are hoisted so you can keep imports/require on top
const sumSpy = jest.fn(() => 42);
jest.mock('./sum', () => sumSpy);
test('Thing', () => {
const thing = new Thing();
//Act
const result = thing.add(1, 2);
//Assert
expect(sumSpy).toHaveBeenCalledTimes(1);
expect(result).toBe(42);
});
You can even provide different mock implementations per test with something like: 您甚至可以为每个测试提供不同的模拟实现,例如:
sumSpy.mockImplementation(() => NaN);
Taken from the Jest Docs. 取自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 https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.