0

我无法模拟一个简单的依赖生成器函数。

//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。

4

1 回答 1

0

问题是 jest 无法知道您在测试中的某个地方使用了 Promise。你要么从你的使用中返回承诺async/await。看看文档

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()
})
于 2017-04-06T06:48:43.087 回答