Jest is the most popular testing framework for JavaScript and integrates well with Next.js.
Installation
bashnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
Configuration
Create jest.config.js:
javascriptconst nextJest = require('next/jest'); const createJestConfig = nextJest({ dir: './', // Path to Next.js app }); const config = { setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], testEnvironment: 'jest-environment-jsdom', moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1', }, }; module.exports = createJestConfig(config);
Create jest.setup.js:
javascriptimport '@testing-library/jest-dom';
Package.json Script
json{ "scripts": { "test": "jest", "test:watch": "jest --watch" } }
The next/jest helper automatically handles:
- SWC/Babel transformation
- CSS/image mocking
- Module path aliases