javascript 开玩笑的模拟实现不适用于 require('')
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32431059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jest mock implementation is not working with require('')
提问by Xiaohe Dong
I want to test one JS which is using one 3rd lib to fetch data, so I am using jest mock that implementation. It is working when I call it directly in the test. However, it is not working when it is used in source code.
我想测试一个使用第三个库来获取数据的 JS,所以我使用 jest 模拟该实现。当我在测试中直接调用它时它正在工作。但是,在源代码中使用时它不起作用。
Here is the code
这是代码
//Source implementation
var reference = require('./reference');
module.exports = {
getResult: function() {
return reference.result();
}
};
//Test code
jest.dontMock('./foo');
jest.dontMock('console');
describe('descirbe', function() {
var foo = require('./foo');
it('should ', function() {
var reference = require('./reference');
reference.result.mockImplementation(function (a, b, c) {
return '123'
});
console.log(foo.getResult()); // undefined
console.log(reference.result()); // 123
});
});
采纳答案by Henrik Andersson
Your order of requires are wrong. When you require ./foobefore setting up your mock referencethen foos referencewill be undefined as per Jest automocking.
您的要求顺序是错误的。当你需要./foo设置你的模拟前,reference然后foo小号reference将不确定按玩笑automocking。
jest.dontMock('./foo');
describe('describe', function() {
it('should ', function () {
var reference = require('./reference');
reference.result.mockImplementation(function (a, b, c) {
return '123';
});
var foo = require('./foo');
console.log('ferr', foo.getResult()); // ferr 123
});
});
回答by CaptainCasey
The line
线
var foo = require('./foo');
var foo = require('./foo');
gets evaluated in the describeand stored in foo.
在 中求值describe并存储在 中foo。
Afterwards, in the itblock, you're mocking that out, but this isn't applying to the old reference foo.
之后,在it块中,您正在嘲笑它,但这不适用于旧的 reference foo。
Putting fooafter the mockImplementationcall will fix the error.
foo在mockImplementation调用之后放置将修复错误。
//Test code
jest.dontMock('./foo');
jest.dontMock('console');
describe('describe', function() {
it('should ', function() {
var reference = require('./reference');
reference.result.mockImplementation(function (a, b, c) {
return '123'
});
var foo = require('./foo');
console.log(foo.getResult()); // undefined
console.log(reference.result()); // 123
});
});

