Setting up Jest with Next.js
Jest and React Testing Library are frequently used together for Unit Testing and Snapshot Testing. This guide will show you how to set up Jest with Next.js and write your first tests.
Good to know: Since
asyncServer Components are new to the React ecosystem, Jest currently does not support them. While you can still run unit tests for synchronous Server and Client Components, we recommend using an E2E tests forasynccomponents.
Quickstart
You can use create-next-app with the Next.js with-jest example to quickly get started:
1npx create-next-app@latest --example with-jest with-jest-app
Manual setup
Since the release of Next.js 12, Next.js now has built-in configuration for Jest.
To set up Jest, install jest and the following packages as dev dependencies:
1npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom2# or3yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom4# or5pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
Generate a basic Jest configuration file by running the following command:
1npm init jest@latest2# or3yarn create jest@latest4# or5pnpm create jest@latest
This will take you through a series of prompts to setup Jest for your project, including automatically creating a jest.config.ts|js file.
Update your config file to use next/jest. This transformer has all the necessary configuration options for Jest to work with Next.js:
1import type { Config } from 'jest'2import nextJest from 'next/jest.js'34const createJestConfig = nextJest({5// Provide the path to your Next.js app to load next.config.js and .env files in your test environment6dir: './',7})89// Add any custom config to be passed to Jest10const config: Config = {11coverageProvider: 'v8',12testEnvironment: 'jsdom',13// Add more setup options before each test is run14// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],15}1617// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async18export default createJestConfig(config)
Under the hood, next/jest is automatically configuring Jest for you, including:
- Setting up
transformusing the Next.js Compiler - Auto mocking stylesheets (
.css,.module.css, and their scss variants), image imports andnext/font - Loading
.env(and all variants) intoprocess.env - Ignoring
node_modulesfrom test resolving and transforms - Ignoring
.nextfrom test resolving - Loading
next.config.jsfor flags that enable SWC transforms
Good to know: To test environment variables directly, load them manually in a separate setup script or in your
jest.config.tsfile. For more information, please see Test Environment Variables.
Optional: Handling Absolute Imports and Module Path Aliases
If your project is using Module Path Aliases, you will need to configure Jest to resolve the imports by matching the paths option in the jsconfig.json file with the moduleNameMapper option in the jest.config.js file. For example:
1{2"compilerOptions": {3"module": "esnext",4"moduleResolution": "bundler",5"baseUrl": "./",6"paths": {7"@/components/*": ["components/*"]8}9}10}
1moduleNameMapper: {2// ...3'^@/components/(.*)$': '<rootDir>/components/$1',4}
Optional: Extend Jest with custom matchers
@testing-library/jest-dom includes a set of convenient custom matchers such as .toBeInTheDocument() making it easier to write tests. You can import the custom matchers for every test by adding the following option to the Jest configuration file:
1setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
Then, inside jest.setup.ts, add the following import:
1import '@testing-library/jest-dom'
Good to know:
extend-expectwas removed inv6.0, so if you are using@testing-library/jest-dombefore version 6, you will need to import@testing-library/jest-dom/extend-expectinstead.
If you need to add more setup options before each test, you can add them to the jest.setup.js file above.
Add a test script to package.json:
Finally, add a Jest test script to your package.json file:
1{2"scripts": {3"dev": "next dev",4"build": "next build",5"start": "next start",6"test": "jest",7"test:watch": "jest --watch"8}9}
jest --watch will re-run tests when a file is changed. For more Jest CLI options, please refer to the Jest Docs.
Creating your first test:
Your project is now ready to run tests. Create a folder called __tests__ in your projectโs root directory.
For example, we can add a test to check if the <Page /> component successfully renders a heading:
1import Link from 'next/link'23export default async function Home() {4return (5<div>6<h1>Home</h1>7<Link href="/about">About</Link>8</div>9)10}
1import '@testing-library/jest-dom'2import { render, screen } from '@testing-library/react'3import Page from '../app/page'45describe('Page', () => {6it('renders a heading', () => {7render(<Page />)89const heading = screen.getByRole('heading', { level: 1 })1011expect(heading).toBeInTheDocument()12})13})
Optionally, add a snapshot test to keep track of any unexpected changes in your component:
1import { render } from '@testing-library/react'2import Page from '../app/page'34it('renders homepage unchanged', () => {5const { container } = render(<Page />)6expect(container).toMatchSnapshot()7})
Running your tests
Then, run the following command to run your tests:
1npm run test2# or3yarn test4# or5pnpm test
Additional Resources
For further reading, you may find these resources helpful:
- Next.js with Jest example
- Jest Docs
- React Testing Library Docs
- Testing Playground - use good testing practices to match elements.