-1

I am using TypeScript and I wish to create unit tests for functions in the same file that call one another.

I have the following function:

export function validateParentFeatureId(parentFeatureId: string | null) {
  const isIdvalid = isParentFeatureIdValid(parentFeatureId);

  if (!isIdvalid) throw new BadRequestError(FeatureErrorMessages.FeatureParentIdInvalid);
}

isParentFeatureIdValid is in the same file as the function above. I don't want the functions to be in different files.

Whenever I create the following unit test it fails:

  it('Should invoke isParentFeatureIdValid when validateParentFeatureId is invoked', () => {
      //const isParentFeatureIdInValidSpy = jest.spyOn(validators, 'isParentFeatureIdValid');
      mockedIsParentFeatureIdInValid.mockReturnValueOnce(true);

      validators.validateParentFeatureId(null)
  
      expect(mockedIsParentFeatureIdInValid).toBeCalled();
  });

I recieve the following error:

expect(jest.fn()).toBeCalled()                                                                                                     
                                                                                                                                       
    Expected number of calls: >= 1                                                                                                     
    Received number of calls:    0  

I'm not sure why it fails when I have always spied on functions and it worked fine.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Karim Fayed
  • 55
  • 10
  • 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 Aug 24 '23 at 11:53
  • (**TL;DR**: [don't](https://stackoverflow.com/a/70066090/3001761). _"I wish to create unit tests to functions in the same file that call one another"_ - that's fine, but you don't need test doubles.) – jonrsharpe Aug 24 '23 at 11:53

0 Answers0