How to Add Jest to Next.js 14
If you follow the official Next.js 14 documentation, Jest won’t install. So I put together a working approach.
1. Install the libraries
yarn add -D @testing-library/dom @testing-library/jest-dom @testing-library/react @types/jest jest jest-environment-jsdom ts-jest ts-node
2. Create jest.config.js
- Caution
- If you create
jest.confit.ts, it won’t recognize TypeScript and Jest won’t run. - It must be at the root path of the project or package.
- If you create
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
/** @type {import('jest').Config} */
const config = {
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// The test environment that will be used for testing
testEnvironment: 'jsdom',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
};
module.exports = createJestConfig(config);
3. Add the test command to package.json
// package.json
{
"scripts": {
// ...
"test": "jest"
// ...
}
}
20250121
Leave a comment