Mocking React Router Hooks
You'll learn how to isolate components from React Router by mocking useNavigate, useParams, and useLocation in your tests.
When testing components that use React Router hooks, you don't want your tests to depend on an actual router setup or real navigation behavior. Instead, you mock these hooks to control their return values and verify interactions.
The Core Pattern
React Router hooks like useNavigate, useParams, and useLocation are just functions exported from the react-router-dom module. Using vi.mock(), you replace them with controlled test doubles:
import { vi } from 'vitest';
import { render, screen } from '@testing-library/react';
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useNavigate: vi.fn(),
useParams: vi.fn(),
useLocation: vi.fn(),
};
});
This partial mock preserves other exports (like Link or Navigate components) while replacing the hooks.
Common Test Scenarios
Mocking useParams to provide route parameters:
import * as router from 'react-router-dom';
vi.mocked(router.useParams).mockReturnValue({ id: '123' });
Mocking useNavigate to verify navigation calls:
const mockNavigate = vi.fn();
vi.mocked(router.useNavigate).mockReturnValue(mockNavigate);
// After user interaction
expect(mockNavigate).toHaveBeenCalledWith('/dashboard');
Mocking useLocation to simulate current route state:
vi.mocked(router.useLocation).mockReturnValue({
pathname: '/profile',
search: '?tab=settings',
hash: '',
state: null,
key: 'default',
});
Think of it like testing a GPS-enabled app by providing fake location data instead of requiring actual satellites.
Key Takeaway: Mock React Router hooks using vi.mock() with partial mocks, then use vi.mocked() to control return values and verify navigation behavior without needing a real router context.