How to spyOn to react custom hook returned value?

1.3k views Asked by At

Here is my custom hook: useCustomModal.ts

export const useCustomModal = (modalType: string) => {
  const setModal = () => {
    // ... functionality here
  };

  const handleModalClose = (modalType: string) => {
    // ... functionality here
    setModal();
    // ...
  };

  return {
    handleModalClose,
    setModal,
  };
};

And here is my test: useCustomModal.ts

import { act } from '@testing-library/react-hooks';

import { useCustomModal } from './useCustomModal';

describe('some', () => {
  it('a test', async () => {
    await act(async () => {
      const actions = useCustomModal('test');
      const spy = jest.spyOn(actions, 'setModal');
      actions.handleModalClose('test');
      expect(spy).toBeCalledTimes(1);
    });
  });
});


Test failed : Expected number of calls: 1 Received number of calls: 0

How to properly spyOn on custom react hooks?

1

There are 1 answers

0
mekwall On

You need to use renderHook in conjunction with act. Something like this:

import { renderHook, act } from '@testing-library/react-hooks';

import { useCustomModal } from './useCustomModal';

describe('some', () => {
  it('a test', () => {
    const { result } = renderHook(() => useCustomModal('test'));
    const spy = jest.spyOn(result.current, 'setModal');
    act(() => {
      result.current.handleModalClose('test');
    });
    expect(spy).toBeCalledTimes(1);
  });
});