【发布时间】:2021-03-31 13:10:38
【问题描述】:
我有代码要编写测试以供以后重构,因此我无法更改代码或任何依赖项。问题来了:
// foo.js
Knex = require('knex')
module.exports ={func}
// calling this inside func will
// have the expected {a:4}
client = Knex()
async function func(){
console.log(client)
return true
}
// foo.spec.js
const foo = require('./foo')
const Knex = require('knex')
jest.mock('knex', ()=>jest.fn())
describe('jest.mockImplementation',()=>{
it('should mock knex',async ()=>{
Knex.mockImplementation(()=>({a:4}))
// alternative, I can put
// const foo = require('./foo')
// here
await foo.func()
})
})
// jest.config.js
module.exports={
"verbose": true,
"testEnvironment": "node",
}
//package.json
{
"dependencies": {
"jest": "^26.6.3",
"knex": "0.19.3"
}
}
我跑:
$ jest --config jest.config.js --runInBand foo.spec.js,我希望有一个{ a : 4} 的控制台日志,但它是undefined。但是请注意,如果我将client 移动到func 中,那么它将记录{a : 4}
或者,如果我将client 保留在原处,将require foo 留在spec.js 中mockImplementation 之后,它将再次具有预期的控制台日志。
我本来希望看到client 在func 之外创建的正确行为,而无需在mockImplementation 之后创建require foo。
为什么会发生这种情况?如何在不移动 client 的情况下获得所需的行为?还有requireing里面的函数也不是最好的。
我创建了这个 repl.it 用于实验;请不要更新它以供他人使用:
【问题讨论】:
标签: javascript node.js jestjs