How to Test Next.js App: Setup, Examples, and Tips
To test a
Next.js app, use Jest as the test runner and @testing-library/react for component testing. Write tests for components, pages, and API routes by rendering them and checking their output or behavior.Syntax
Testing a Next.js app typically involves these parts:
- Import the component or page you want to test.
- Render it using
@testing-library/reactto simulate how it appears in the browser. - Assert expected output or behavior using Jest's
expectfunction. - Mock Next.js features like routing or API calls if needed.
javascript
import { render, screen } from '@testing-library/react'; import Component from '../path/to/component'; test('renders component text', () => { render(<Component />); expect(screen.getByText('Hello')).toBeInTheDocument(); });
Example
This example shows how to test a simple Next.js component that displays a greeting message.
javascript
import { render, screen } from '@testing-library/react'; import Greeting from '../components/Greeting'; describe('Greeting component', () => { it('shows the greeting message', () => { render(<Greeting name="Alice" />); expect(screen.getByText('Hello, Alice!')).toBeInTheDocument(); }); }); // Greeting.js component export default function Greeting({ name }) { return <h1>Hello, {name}!</h1>; }
Output
PASS Greeting component shows the greeting message
Common Pitfalls
Common mistakes when testing Next.js apps include:
- Not wrapping components with necessary providers like
next/routeror context, causing errors. - Testing implementation details instead of user-visible output.
- Forgetting to mock Next.js features like
useRouterwhen testing pages. - Running tests without proper Jest configuration for Next.js.
javascript
import { render } from '@testing-library/react'; import Page from '../pages/index'; // Wrong: No router mock, will error if page uses useRouter // render(<Page />); // Right: Mock useRouter before rendering import { useRouter } from 'next/router'; jest.mock('next/router', () => ({ useRouter: () => ({ route: '/' }) })); render(<Page />);
Quick Reference
Tips for testing Next.js apps:
- Use
Jestwith@testing-library/reactfor best results. - Mock Next.js hooks like
useRouterto avoid errors. - Test user-visible output, not internal state.
- Configure Jest with
next/jestpreset for Next.js support. - Use
jest.mockto mock API calls or modules.
Key Takeaways
Use Jest and @testing-library/react to test Next.js components and pages.
Mock Next.js features like useRouter to prevent errors in tests.
Focus tests on what users see and interact with, not internal details.
Configure Jest properly with next/jest preset for Next.js compatibility.
Write simple, clear tests that check rendered output and behavior.