0

Let's say I have a super simplified utility class, utilities.ts:

export const one = (someParam: Object) => {
  // some logic
}
export const two = (someArr: Object[]) => {
  const modifiedValues = [];
  for(const i of someArr) {
    modifiedValues.push(one(i));
  }
  return modifiedValues;
}

I want to test that two() calls one() 3 times when someArr has length 3. I don't care to test what one() is doing because I'm testing that elsewhere. I'm not able to get jest.spyOn to work as I would expect. Per other discussions I've tried:

import * as utils from '../utils';

// inside test block
const oneSpy = jest.spyOn(utils, 'one').mockImplementation(); // tried without mockImplementation as well
const result = utils.two( /* some test array of length 3 */);

expect(oneSpy).toHaveBeenCalledTimes(3);

and am getting a failure that is has received 0 calls. I don't want to do jest.mock because I do want to test the actual functionality, just not in this particular test.

What am I missing here?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Dan L
  • 235
  • 4
  • 12
  • See https://stackoverflow.com/a/70066090/3001761. Your current attempt doesn't work because two doesn't call one via the module, contorting the implementation to make the testing approach work is a bad move. – jonrsharpe Sep 19 '22 at 20:32
  • I definitely don't want to contort the implementation (I agree, a bad move). However the functionality of `one()` is really of no true testing concern. In the particular case it is going to do a conversion from a service response to a UI representation. Said conversion `one()` takes two properties from `two()` and returns a simplified type. If that conversion got tweaked then the tests for `two()` would break (unnecessarily imo). `one()` would have proper coverage in separate tests already. Obviously this is a simple example but becomes more relevant with more complex functionality. – Dan L Sep 19 '22 at 23:28
  • Change `modifiedValues.push(one(i));` to `modifiedValues.push(this.one(i));` – hoangdv Sep 20 '22 at 01:24
  • @hoangdv this is not a TS class and there is no `this` context. – Dan L Sep 20 '22 at 13:20
  • Does this answer your question? [How to mock functions in the same module using Jest?](https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest) – jonrsharpe Sep 20 '22 at 13:56
  • @jonrsharpe unfortunately no, Jest still says it was not called – Dan L Sep 20 '22 at 15:16
  • There are 11 answers on that page, you're going to have to be more specific about what exactly you've done. – jonrsharpe Sep 20 '22 at 15:17
  • When you call `utils.two` then `this` will become `utils` – hoangdv Sep 21 '22 at 04:01

0 Answers0