Jest spy on a function inside a custom hook

Viewed 1654

I have a custom hook called useCustom, that implements a function called doSomething. In my react component I want to spy on the doSomething that it has been called with certain values. But it never gets called. What would be the proper way to mock or spy on that doSomething method?

This is what I tried:

myComponent.tsx

...
const { doSomething} = useCustom();
doSomething('a','b');
...

useCustom.ts

export const useCustom= () => {
  const doSomething = (param1, param2): void => {
    ...
  };

  return { doSomething };

myComponent.spec.ts

it('should call dosomething', () => {
    const doSomethingSpy= jest.spyOn(useCustom(), 'doSomething');
    ...
    expect(doSomethingSpy).toHaveBeenCalledWith('a','b');
});
1 Answers

I now managed to do it like this:

import * as useCustomHook from '@hooks/useCustom';

it('should call dosomething', () => {
    const doSomethingMock= jest.fn();
    jest.spyOn(useCustomHook, 'useCustom').mockImplementation(() => {
      return {
         doSomething: doSomethingMock,
      };
     });
     ...
     expect(doSomethingMock).toHaveBeenCalledWith('a','b');
 });
Related