Q1: How do you test Server Components?
Challenge: Server Components are async functions that may access headers, cookies, or databases directly.
Unit Testing: Since they are just functions, you can test them by mocking the data they fetch or the Next.js headers/cookies API.
Integration Testing: It is often better to test them via E2E tests (Playwright/Cypress) or by rendering the parent page that uses them, as traditional React testing libraries (RTL) run in a jsdom environment which doesn't fully support the RSC protocol.
Q2: What is the recommended tool for E2E testing in Next.js?
Playwright: It is the recommended tool by the Next.js team.
Why?
- Supports testing across all modern browsers.
- Can handle multiple tabs and users.
- Works well with Next.js's async nature and hydration.
- Can easily mock network requests or run against a real production build.
Q3: How do you mock `next/navigation` (useRouter, usePathname) in unit tests?
When using Jest and React Testing Library, you need to mock the module.
jest.mock('next/navigation', () => ({
useRouter: () => ({
push: jest.fn(),
replace: jest.fn(),
prefetch: jest.fn(),
}),
usePathname: () => '/current-path',
useSearchParams: () => new URLSearchParams({ query: 'test' }),
}));
This allows you to assert that router.push was called with the correct arguments.