0

I am having trouble mocking a simple 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()
  })
})

which errors out as execute is never called, although when I console log inside of actualFunction is saw that execute was called.

l2silver
  • 5
  • 1
  • 3

1 Answers1

0

The problem is that jest cant know you using a promise somewhere in your test. You have either return the promise from you use async/await. Have a look at the 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()
})
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • I didn't realize that you had to return the promise, but this still doesnt make sense. Where doe generateFunction come from in the examples you provided? I realized I didn't provide that context in the question and have added it now – l2silver Apr 06 '17 at 20:39
  • Ah sorry, you have to import them as well. The imported version is then the mocked one and you can test on it. Updated my answer. – Andreas Köberle Apr 06 '17 at 20:41
  • Sorry, the problem with the generator function is that it has to generate an instance of itself, and I think this is where the confusion comes in. If you were importing. If you look closely at the example, the imported generatorFunction then creates the generateFunction. I really should have been much clearer with my question, i'll change it now – l2silver Apr 06 '17 at 20:48