Why Jest with Next.js?
Jest is a popular testing framework that pairs well with React Testing Library to validate component behavior and UI rendering. While Jest doesn’t currently support async Server Components, it’s perfect for testing synchronous Server and Client Components. For async components, consider using end-to-end testing tools like Playwright or Cypress.
Quickstart: Scaffold with create-next-app
The fastest way to get started is by using the official example:
npx create-next-app@latest --example with-jest with-jest-app
This sets up a Next.js project pre-configured with Jest.
Manual Setup: Step-by-Step
If you prefer manual control, here’s how to configure Jest from scratch:
1. Install Dependencies
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
2. Initialize Jest Config
npm init jest@latest
This creates a jest.config.ts
file. Update it to use next/jest
:
import type { Config } from 'jest'
import nextJest from 'next/jest.js'
const createJestConfig = nextJest({ dir: './' })
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
}
export default createJestConfig(config)
Optional Enhancements
Absolute Imports & Module Aliases
If you're using path aliases in tsconfig.json
, map them in Jest:
"paths": {
"@/components/*": ["components/*"]
}
moduleNameMapper: {
'^@/components/(.*)$': '<rootDir>/components/$1',
}
Custom Matchers
Enable matchers like .toBeInTheDocument()
by adding this to your config:
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
And in jest.setup.ts
:
import '@testing-library/jest-dom'
Add Test Scripts
Update your package.json
:
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}
Writing Your First Test
Create a __tests__
folder and add a simple test:
// __tests__/page.test.jsx import '@testing-library/jest-dom' import { render, screen } from '@testing-library/react' import Page from '../app/page' describe('Page', () => { it('renders a heading', () => { render(<Page />) const heading = screen.getByRole('heading', { level: 1 }) expect(heading).toBeInTheDocument() }) })
Running Tests
Use your terminal:
npm run test
Setting up Jest in your Next.js project doesn’t have to be daunting. With built-in support and powerful testing libraries, you can ensure your components behave as expected—giving you confidence in every deploy.
Seng Seang Leng
Web Developer
ព័ត៌មានថ្មីៗ - បច្ចេកវិទ្យា
មើលបន្ថែមទៀត