react

T.I.L.

Mock module inside test

How to mock module implementation inside a test with jest

Sometimes you are testing a component and need to mock a module (in this case I needed to mock a zustand store), but with the exemple of "next/navigation" mock, you are mocking the module for entire test suit on the file that you declare the jest.mock(). But, if you want to mock a specific implementation for each test? So first, with need to declare the module mock, without pass the implementation function:

jest.mock('../../stores/sounds-state-store')

In this case we are mocking "../../stores/sounds-state-store" module

And, inside each test, we will use the jest.Mock.mockImplementation() function to mock the implementation of module inside it/test scope:

the store we want to mock is useSoundsStateStore, from '../../stores/sounds-state-store'

useSoundsStateStore.mockImplementation(
  () =>
    [{ active: true, id: 'd4ad48e', loaded: true, volume: 1 }] as SoundState[]
)

Full code:

// other imports...
import { SoundState, useSoundsStateStore } from '../../stores/sounds-state-store'
 
jest.mock('../../stores/sounds-state-store')
 
describe('Clear Button', () => {
  // tests...
 
  it('should not be disabled', async () => {
    ;(useSoundsStateStore as unknown as jest.Mock).mockImplementation(
      () =>
        [
          { active: true, id: 'd4ad48e', loaded: true, volume: 1 }
        ] as SoundState[]
    )
 
    render(<ClearButton />)
 
    const button = await screen.findByRole('button', { name: /clear/i })
 
    expect(button.getAttribute('disabled')).toBeNull()
  })
 
  // tests...
})

Note that we use:

;(useSoundsStateStore as unknown as jest.Mock).mockImplementation()

instead of:

useSoundsStateStore.mockImplementation()

Because it's a typescript project, and we need to tell the ts compiler that useSoundsStateStore have jest.Mock functions on this scope.

references:

Mock "next/navigation" with Jest

How to fix error "invariant expected app router to be mounted" when test Next.js hooks/components

Next.js: 14.0.3

When you try to test a component or hook that uses some function from "next/navigation" module (like useRouter, useSearchParams, useSearchParams, etc.), you may come across the error:

● Test suite failed to run
 
  invariant expected app router to be mounted
 
    5 |
    6 | export default function useQueryState(key: string, defaultValue: string = '') {
  > 7 |   const router = useRouter()
      |                           ^
    8 |   const searchParams = useSearchParams()
    9 |   const pathname = usePathname()
   10 |

This happening because the "next/navigation" just works when app router was monted, to solve this, you need to mock the entire module. Put this before all your describes and it/tests:

jest.mock('next/navigation', () => ({
  useRouter: jest.fn(() => ({
    replace: jest.fn()
  })),
  useSearchParams: jest.fn(() => ({
    get: jest.fn()
  })),
  usePathname: jest.fn()
}))

references: https://github.com/vercel/next.js/discussions/48937