0
helpers.ts

export function doThing() { 
// some stuff
}
myClass.ts
___

import { doThing } from './helpers.ts'

class myClass {

function someFunction(firstArg, secondArg) {
  const thing = someThirdThing;
  doThing(firstArg, secondArg, someThirdArg);
 }
}

What I've tried

myClass.spec.ts

import * as helpers from './helpers.ts'

describe('someFunction' () => {
 it('calls doThing with the correct parameters', () => {
  spyOn(helpers, 'doThing');
  const myClass = new MyClass();
  
  myClass.someFunction(first, second);

  expect(helpers.doThing).toHaveBeenCalledWith(first, second, someThirdThing);
 }
}
___

What I end up with when I debug is that I can see that my debugger is getting into the actual method itself, which is fine because I expect jest to call the actual implementation for the spy. However I get a 'Expected: my assertation, 'calls: 0'

I've run myself pretty crazy and consider myself at least half decent at tests. But for the life of me when it comes to spying on exported functions that aren't injected through classes, I end up bewildered.

I've looked at: SpyOn individually exported ES6 functions but from my understanding it doesn't track because my example has different modules. Thank you in advance for kindness in your response.

1 Answers1

0

i think its better to mock the function call when testing the parent function like this:

describe('someFunction' () => {
 it('calls doThing with the correct parameters', () => {
  jest.spyOn(helpers, 'doThing').mockImplementation;
  const myClass = new MyClass();
  
  myClass.someFunction(first, second);

  expect(helpers.doThing).toHaveBeenCalledWith(first, second, someThirdThing);
 }
}

you can test the "doThing" function in a seperate unit test helper.spec.ts.

PS. in a newer version of jest i need to use jest.spyOn(class, 'fucntion').mockImplementation. In an older version i was using spyOn(class, 'function').and.stub(); maybe because of jasmine types.

Fiehra
  • 659
  • 6
  • 23