I have
// mod1.js
const f = (_n) => console.info('a:', _n) || _n * 2
module.exports = { f }
// mod2.js
const { f } = require('./mod1')
const g = (_n) => 3 * f(_n)
module.exports = { g }
and a test file
describe('mod2', () => {
it('should check 1', () => {
const { g } = require('../src/mod2')
expect(g(2)).toEqual(12)
})
it('should check 2', () => {
const mod1 = require('../src/mod1')
jest.spyOn(mod1, 'f').mockImplementation(_n => _n * 4)
const { g } = require('../src/mod2')
expect(g(2)).toEqual(24)
})
it('should check 3', () => {
const mod1 = require('../src/mod1')
jest.spyOn(mod1, 'f').mockImplementation(_n => _n * 5)
const { g } = require('../src/mod2')
expect(g(2)).toEqual(30)
})
})
Well, second and third test fail because apparently the original function (loaded by the first test) is used.
If I have
// mod2.js
const mod1 = require('./mod1')
const g = (_n) => 3 * mod1.f(_n)
module.exports = { g }
all is good!
You can check this repo: https://github.com/oliviera9/test-jest-require-cache