0

I have a custom hook called useInitialSetup that returns a key-value dictionary object. It's being consumed in App.tsx.

In App.test.tsx, I have a suite of unit tests written using Jest and React Testing Library.

Is it possible to mock useInitialSetup in only a selection of unit tests, but not all?

Here's what I have tried in App.test.tsx:

jest.mock('../../hooks/useInitialSetup', () => {
  return jest.fn(() => ({
    loading: mockLoading,
    suspendedTrial: mockSuspendedTrial,
    maxTrials: mockMaxTrials,
    reachedMaxTrials: mockReachedMaxTrials,
  }));
});

it('Unit test that uses a mocked version of useInitialSetup', () => {
  render(<App/>)
  ...
})

it('Unit test that uses the real implementation of useInitialSetup', () => {
  jest.dontMock('../../hooks/useInitialSetup')
  render(<App/>)
  ...
})

Unit test #2 still uses the mocked version of useInitialSetup.

Cog
  • 1,545
  • 2
  • 15
  • 27
  • 1
    Does this answer your question? [Jest Mock module per test](https://stackoverflow.com/a/66326501/1870780) – juliomalves Apr 22 '21 at 19:36
  • 1
    @juliomalves Thanks for posting that link. I didn't quite go with that solution. This was a closer match to what I was looking for: https://stackoverflow.com/a/62138485/1930938 – Cog Apr 22 '21 at 21:34

1 Answers1

1

Here's what I ended up doing. This lets me mock the output of my useInitialSetup custom hook for this one selected unit test. Any subsequent unit tests will use the default implementation of this hook.

import * as useInitialSetup from '../../hooks/useInitialSetup';

it('Test', () => {
  const spy = jest.spyOn(useInitialSetup, 'default');
  spy.mockReturnValue({
    loading: false,
    reachedMaxTrials: true,
    errorCheckingCanCreateInstance: false,
    errorFetchingUser: false,

    // @ts-ignore
    suspendedTrial: mockSuspendedTrial,
    resetChecks: () => {},
    maxTrials: 1,
  });

  render(setupComponent());
  expect(true).toBe(true) // or whatever assertion you want
  spy.mockRestore();
})
Cog
  • 1,545
  • 2
  • 15
  • 27