2

How can you spy on a function that has been exported, but also called in a function like this:

File 1:

export function myFunction(){
  // do stuff
  return myOtherFunction()
}

export function myOtherFunction(){
  // do stuff
}

File 2:

import * as helpers from './helpers'
beforeEach(()=>{
  spyOn(helpers, 'myOtherFunction');
});
it('should call myOtherFunction', ()=>{
  helpers.myFunction();
  expect(helpers.myOtherFunction).toHaveBeenCalled()
});

The problem with this is that myOtherFunction will never be called, because jasmine is spying on the wrong object. myFunction will call the local function and the jasmine test will expect the exported variable to get called, they are different objects.

Samuel Thompson
  • 2,429
  • 4
  • 24
  • 34
  • 1
    This question looks similar to [this other question](https://stackoverflow.com/q/49538472/6361314) I came across some time ago. – JJWesterkamp Apr 09 '18 at 20:49
  • @JeffreyWesterkamp I agree. I think it is a duplicate, but that other guys solution only works with a class I am exporting just a function. – Samuel Thompson Apr 09 '18 at 21:23
  • 1
    The problem here is identical actually. Only the `helpers.myOtherFunction` reference in **File 2** is overwritten. `myFunction` however uses a direct local reference. that is also why your expectation fails. The overwritten reference in **File 2** is actually never called, _only the actual implementation_. The local reference is never going to be anything else, unless explicitly overwritten from within **File 1**. – JJWesterkamp Apr 09 '18 at 21:27

0 Answers0