Given a module under test sut.js
const { dependencyFunc } = require('./dep')
module.exports = () => {
return dependencyFunc()
}
with dependency dep.js
module.exports = {
dependencyFunc: () => 'we have hit the dependency'
}
and some tests:
describe('mocking in beforeEach', () => {
let sut
let describeScope
beforeEach(() => {
let beforeEachScope = false
describeScope = false
console.log('running before each', { beforeEachScope, describeScope })
jest.setMock('./dep', {
dependencyFunc: jest.fn().mockImplementation(() => {
const returnable = { beforeEachScope, describeScope }
beforeEachScope = true
describeScope = true
return returnable
})
})
sut = require('./sut')
})
it('first test', () => {
console.log(sut())
})
it('second test', () => {
console.log(sut())
})
})
I get the following output:
me$ yarn test test.js
yarn run v1.22.5
$ jest test.js
PASS ./test.js
mocking in beforeEach
✓ first test (17 ms)
✓ second test (2 ms)
console.log
running before each { beforeEachScope: false, describeScope: false }
at Object.<anonymous> (test.js:9:13)
console.log
{ beforeEachScope: false, describeScope: false }
at Object.<anonymous> (test.js:22:13)
console.log
running before each { beforeEachScope: false, describeScope: false }
at Object.<anonymous> (test.js:9:13)
console.log
{ beforeEachScope: true, describeScope: false }
at Object.<anonymous> (test.js:26:13)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.248 s, estimated 2 s
Ran all test suites matching /test.js/i.
✨ Done in 3.56s.
I expect the output for both tests to be { beforeEachScope: false, describeScope: false }
. I.e., I expect both beforeEachScope
and describeScope
variables to be reset to false
regardless of whether they were declared in the beforeEach
scope or the describe
scope. In my real test I consider it cleaner to have it in the beforeEach
scope as it is not needed elsewhere. What's going on? What scope is the Jest stuff using?