Mocking Next.js useRouter with Jest is pivotal for robust testing in a Next.js environment. Follow this detailed guide, complete with code snippets, to master the process:
Step-by-Step Guide:
1. Setting Up Jest Mock:
In your Jest setup file (e.g., setup-jest.ts), create a mock for ‘next/router’ to mock the useRouter function using Jest’s jest.fn().
// setup-jest.ts
jest.mock('next/router', () => ({
useRouter: jest.fn()
}))
2. Testing Components:
In your test files (e.g., components.test.tsx), import useRouter from ‘next/router’ and create a mocked useRouter function using Jest’s jest.Mock.
import { useRouter } from 'next/router'
const mockedUseRouter = useRouter as jest.Mock
3. Testing Navigation Functionality:
Proceed to test navigation scenarios. For instance, test whether a click on ‘My Profile’ navigates to the ‘/my-profile’ route.
test('should navigate to my-profile', () => {
const mockRouter = { push: jest.fn() }
mockedUseRouter.mockReturnValue(mockRouter)
renderComponent()
fireEvent.click(screen.getByText('My Profile')
expect(mockRouter.push).toHaveBeenCalledWith('/my-profile')
)
Implement these steps in your testing suite to effectively mock Next.js useRouter using Jest, ensuring precise and reliable testing of navigation functionalities within your Next.js application.