开玩笑模拟依赖生成器函数

jest mock dependency generator function

我在模拟一个简单的依赖生成器函数时遇到问题。

//generatorFunction.js
export default ()=>({execute: (arg1)=>Promise.resolve(arg1)})

//actualFunction.js
import generate from 'generatorFunction'
export default (arg1)=>generate(arg1)

//actualFunction.test.js
import actualFunction from './actualFunction'
import generatorFunction from './generatorFunction'
const resultingGeneratedFunction = generatorFunction();

jest.mock('generatorFunction', ()=>jest.fn(()=>({execute: ()=>Promise.resolve()})))
it('calls generateFunction', function(done){
  actualFunction(1).then(()=>{
   expect(resultingGeneratedFunction.execute).toHaveBeenCalledOnce()
   done()
  })
})

虽然当我在 actualFunction 内部控制台登录时看到调用了 execute,但从未调用过 execute 的错误。

问题是 jest 无法知道您在测试中的某个地方使用了 promise。您有 return 您使用 async/await 的承诺。看看 docs

import actualFunction from './actualFunction'
import generate from 'generatorFunction'

jest.mock('generatorFunction', ()=>jest.fn(()=>({execute: ()=>Promise.resolve()})))
it('calls generateFunction', function(){
  return actualFunction(1).then(()=>{
   expect(generateFunction.execute).toHaveBeenCalledOnce()
  })
})

import actualFunction from './actualFunction'
import generate from 'generatorFunction'

jest.mock('generatorFunction', ()=>jest.fn(()=>({execute: ()=>Promise.resolve()})))
it('calls generateFunction', async function(){
  const value = await actualFunction(1)
  expect(generateFunction.execute).toHaveBeenCalledOnce()
})