【发布时间】:2021-02-12 10:50:45
【问题描述】:
给定一个正在测试的模块sut.js
const { dependencyFunc } = require('./dep')
module.exports = () => {
return dependencyFunc()
}
依赖dep.js
module.exports = {
dependencyFunc: () => 'we have hit the dependency'
}
还有一些测试:
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())
})
})
我得到以下输出:
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.
我希望这两个测试的输出都是{ beforeEachScope: false, describeScope: false }。即,我希望beforeEachScope 和describeScope 变量都被重置为false,无论它们是在beforeEach 范围内还是在describe 范围内声明的。在我的真实测试中,我认为将它放在beforeEach 范围内会更干净,因为其他地方不需要它。这是怎么回事? Jest 使用的范围是什么?
【问题讨论】:
标签: javascript scope jestjs