0

I'm trying to write some Jest tests to test if when a function call is made, its inner functions are also invoked. My functions look like this :

fileCoordinator.js

export const save(var1, var2) {
  saveToFile(var1,var2)
  return var1 + var2
}

export saveToFile(var1, var2){
  console.log("saved")
}

My spec file looks like this:

import * fileCoordinator from '../path'

it('should call the inner function', () => {
  let spy = jest.spyOn(fileCoordinator, "save")
  let spy1 = jest.spyOn(fileCoordinator, "saveToFile")
        
  fileCoordinator.save(1,2)
  
  expect(spy1).toHaveBeenCalled()

})

For some reason, this test fails because the function saveToFile was never called. Any help would be greatly appreciated.

paulgio
  • 612
  • 2
  • 8
  • 21
  • Unrelated, but why set a return value on spy1? – Dave Newton Aug 17 '20 at 01:34
  • Not 100% sure. I've just been going off some stuff I found online that had the spy return value mocked. It shouldn't make a difference though for now at least – paulgio Aug 17 '20 at 01:42
  • 1
    Right, but that function only has an implicit return (e.g., undefined). – Dave Newton Aug 17 '20 at 02:06
  • True it could cause an issue later on so I'll get rid of it. – paulgio Aug 17 '20 at 02:13
  • You can't mock a function that is defined and used in the same module. This is a fundamental property of JS, there's no way how this can work without patching the code. Separate them to different modules if you really need one of them mocked. See https://stackoverflow.com/a/63336179/3731501 – Estus Flask Aug 17 '20 at 06:12

1 Answers1

0

These function definitions are not valid

export const save(var1, var2) {
  saveToFile(var1,var2)
  return var1 + var2
}

give a syntax error of Missing initializer in const declaration

Try

export const save = function(var1, var2) {
  saveToFile(var1,var2)
  return var1 + var2
}

or

export function save(var1, var2) {
  saveToFile(var1,var2)
  return var1 + var2
}
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60