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.
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
});
});
Your order of requires are wrong. When you require ./foo
before setting up your mock reference
then foo
s reference
will be undefined as per Jest 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
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With