Jest mock implementation does not work with require ('')

I want to test one JS that uses one third library to retrieve data, so I use jest mock for this implementation. It works when I call it directly in the test. However, it does not work when it is used in the 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 }); }); 
+5
source share
2 answers

Your order of requests is incorrect. When you need ./foo before setting up your reference layout, then foo reference will be undefined according to Jest automocking.

 jest.dontMock('./foo'); describe('descirbe', 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 }); }); 
+2
source

Line

var foo = require('./foo');

evaluated in describe and stored in foo .

Then in the it block you mock it, but this does not apply to the old foo link.

Putting foo after calling mockImplementation will fix the error.

 //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 }); }); 
+2
source

All Articles