Testing

Examples

Learn how to set up Next.js with commonly used testing tools: Cypress, Playwright, and Jest with React Testing Library.

Cypress

Cypress is a test runner used for End-to-End (E2E) and Integration Testing.

Quickstart

You can use create-next-app with the with-cypress example to quickly get started.

  1. npx create-next-app@latest --example with-cypress with-cypress-app

Manual setup

To get started with Cypress, install the cypress package:

  1. npm install --save-dev cypress

Add Cypress to the package.json scripts field:

  1. "scripts": {
  2. "dev": "next dev",
  3. "build": "next build",
  4. "start": "next start",
  5. "cypress": "cypress open",
  6. }

Run Cypress for the first time to generate examples that use their recommended folder structure:

  1. npm run cypress

You can look through the generated examples and the Writing Your First Test section of the Cypress Documentation to help you get familiar with Cypress.

Creating your first Cypress integration test

Assuming the following two Next.js pages:

  1. // pages/index.js
  2. import Link from 'next/link'
  3. export default function Home() {
  4. return (
  5. <nav>
  6. <Link href="/about">
  7. <a>About</a>
  8. </Link>
  9. </nav>
  10. )
  11. }
  1. // pages/about.js
  2. export default function About() {
  3. return (
  4. <div>
  5. <h1>About Page</h1>
  6. </div>
  7. )
  8. }

Add a test to check your navigation is working correctly:

  1. // cypress/integration/app.spec.js
  2. describe('Navigation', () => {
  3. it('should navigate to the about page', () => {
  4. // Start from the index page
  5. cy.visit('http://localhost:3000/')
  6. // Find a link with an href attribute containing "about" and click it
  7. cy.get('a[href*="about"]').click()
  8. // The new url should include "/about"
  9. cy.url().should('include', '/about')
  10. // The new page should contain an h1 with "About page"
  11. cy.get('h1').contains('About Page')
  12. })
  13. })

You can use cy.visit("/") instead of cy.visit("http://localhost:3000/") if you add "baseUrl": "http://localhost:3000" to the cypress.json configuration file.

Running your Cypress tests

Since Cypress is testing a real Next.js application, it requires the Next.js server to be running prior to starting Cypress. We recommend running your tests against your production code to more closely resemble how your application will behave.

Run npm run build and npm run start, then run npm run cypress in another terminal window to start Cypress.

Note: Alternatively, you can install the start-server-and-test package and add it to the package.json scripts field: "test": "start-server-and-test start http://localhost:3000 cypress" to start the Next.js production server in conjunction with Cypress. Remember to rebuild your application after new changes.

Getting ready for Continuous Integration (CI)

You will have noticed that running Cypress so far has opened an interactive browser which is not ideal for CI environments. You can also run Cypress headlessly using the cypress run command:

  1. // package.json
  2. "scripts": {
  3. //...
  4. "cypress": "cypress open",
  5. "cypress:headless": "cypress run",
  6. "e2e": "start-server-and-test start http://localhost:3000 cypress",
  7. "e2e:headless": "start-server-and-test start http://localhost:3000 cypress:headless"
  8. }

You can learn more about Cypress and Continuous Integration from these resources:

Playwright

Playwright is a testing framework that lets you automate Chromium, Firefox, and WebKit with a single API. You can use it to write End-to-End (E2E) and Integration tests across all platforms.

Quickstart

The fastest way to get started is to use create-next-app with the with-playwright example. This will create a Next.js project complete with Playwright all set up.

  1. npx create-next-app@latest --example with-playwright with-playwright-app

Manual setup

You can also use npm init playwright to add Playwright to an existing NPM project.

To manually get started with Playwright, install the @playwright/test package:

  1. npm install --save-dev @playwright/test

Add Playwright to the package.json scripts field:

  1. "scripts": {
  2. "dev": "next dev",
  3. "build": "next build",
  4. "start": "next start",
  5. "test:e2e": "playwright test",
  6. }

Creating your first Playwright end-to-end test

Assuming the following two Next.js pages:

  1. // pages/index.js
  2. import Link from 'next/link'
  3. export default function Home() {
  4. return (
  5. <nav>
  6. <Link href="/about">
  7. <a>About</a>
  8. </Link>
  9. </nav>
  10. )
  11. }
  1. // pages/about.js
  2. export default function About() {
  3. return (
  4. <div>
  5. <h1>About Page</h1>
  6. </div>
  7. )
  8. }

Add a test to verify that your navigation is working correctly:

  1. // e2e/example.spec.ts
  2. import { test, expect } from '@playwright/test'
  3. test('should navigate to the about page', async ({ page }) => {
  4. // Start from the index page (the baseURL is set via the webServer in the playwright.config.ts)
  5. await page.goto('http://localhost:3000/')
  6. // Find an element with the text 'About Page' and click on it
  7. await page.click('text=About')
  8. // The new URL should be "/about" (baseURL is used there)
  9. await expect(page).toHaveURL('http://localhost:3000/about')
  10. // The new page should contain an h1 with "About Page"
  11. await expect(page.locator('h1')).toContainText('About Page')
  12. })

You can use page.goto("/") instead of page.goto("http://localhost:3000/"), if you add “baseURL”: “http://localhost:3000” to the playwright.config.ts configuration file.

Running your Playwright tests

Since Playwright is testing a real Next.js application, it requires the Next.js server to be running prior to starting Playwright. It is recommended to run your tests against your production code to more closely resemble how your application will behave.

Run npm run build and npm run start, then run npm run test:e2e in another terminal window to run the Playwright tests.

Note: Alternatively, you can use the webServer feature to let Playwright start the development server and wait until it’s fully available.

Running Playwright on Continuous Integration (CI)

Playwright will by default run your tests in the headless mode. To install all the Playwright dependencies, run npx playwright install-deps.

You can learn more about Playwright and Continuous Integration from these resources:

Jest and React Testing Library

Jest and React Testing Library are frequently used together for Unit Testing. There are three ways you can start using Jest within your Next.js application:

  1. Using one of our quickstart examples
  2. With the Next.js Rust Compiler
  3. With Babel

The following sections will go through how you can set up Jest with each of these options:

Quickstart

You can use create-next-app with the with-jest example to quickly get started with Jest and React Testing Library:

  1. npx create-next-app@latest --example with-jest with-jest-app

Setting up Jest (with the Rust Compiler)

Since the release of Next.js 12, Next.js now has built-in configuration for Jest.

To set up Jest, install jest, jest-environment-jsdom, @testing-library/react, @testing-library/jest-dom:

  1. npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom

Create a jest.config.js file in your project’s root directory and add the following:

  1. // jest.config.js
  2. const nextJest = require('next/jest')
  3. const createJestConfig = nextJest({
  4. // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  5. dir: './',
  6. })
  7. // Add any custom config to be passed to Jest
  8. /** @type {import('jest').Config} */
  9. const customJestConfig = {
  10. // Add more setup options before each test is run
  11. // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  12. // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
  13. moduleDirectories: ['node_modules', '<rootDir>/'],
  14. testEnvironment: 'jest-environment-jsdom',
  15. }
  16. // createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
  17. module.exports = createJestConfig(customJestConfig)

Under the hood, next/jest is automatically configuring Jest for you, including:

  • Setting up transform using SWC
  • Auto mocking stylesheets (.css, .module.css, and their scss variants) and image imports
  • Loading .env (and all variants) into process.env
  • Ignoring node_modules from test resolving and transforms
  • Ignoring .next from test resolving
  • Loading next.config.js for flags that enable SWC transforms

Note: To test environment variables directly, load them manually in a separate setup script or in your jest.config.js file. For more information, please see Test Environment Variables.

Setting up Jest (with Babel)

If you opt out of the Rust Compiler, you will need to manually configure Jest and install babel-jest and identity-obj-proxy in addition to the packages above.

Here are the recommended options to configure Jest for Next.js:

  1. // jest.config.js
  2. module.exports = {
  3. collectCoverage: true,
  4. // on node 14.x coverage provider v8 offers good speed and more or less good report
  5. coverageProvider: 'v8',
  6. collectCoverageFrom: [
  7. '**/*.{js,jsx,ts,tsx}',
  8. '!**/*.d.ts',
  9. '!**/node_modules/**',
  10. '!<rootDir>/out/**',
  11. '!<rootDir>/.next/**',
  12. '!<rootDir>/*.config.js',
  13. '!<rootDir>/coverage/**',
  14. ],
  15. moduleNameMapper: {
  16. // Handle CSS imports (with CSS modules)
  17. // https://jestjs.io/docs/webpack#mocking-css-modules
  18. '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
  19. // Handle CSS imports (without CSS modules)
  20. '^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
  21. // Handle image imports
  22. // https://jestjs.io/docs/webpack#handling-static-assets
  23. '^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i': `<rootDir>/__mocks__/fileMock.js`,
  24. // Handle module aliases
  25. '^@/components/(.*)$': '<rootDir>/components/$1',
  26. },
  27. // Add more setup options before each test is run
  28. // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  29. testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
  30. testEnvironment: 'jsdom',
  31. transform: {
  32. // Use babel-jest to transpile tests with the next/babel preset
  33. // https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
  34. '^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
  35. },
  36. transformIgnorePatterns: [
  37. '/node_modules/',
  38. '^.+\\.module\\.(css|sass|scss)$',
  39. ],
  40. }

You can learn more about each configuration option in the Jest docs.

Handling stylesheets and image imports

Stylesheets and images aren’t used in the tests but importing them may cause errors, so they will need to be mocked. Create the mock files referenced in the configuration above - fileMock.js and styleMock.js - inside a __mocks__ directory:

  1. // __mocks__/fileMock.js
  2. module.exports = {
  3. src: '/img.jpg',
  4. height: 24,
  5. width: 24,
  6. blurDataURL: 'data:image/png;base64,imagedata',
  7. }
  1. // __mocks__/styleMock.js
  2. module.exports = {}

For more information on handling static assets, please refer to the Jest Docs.

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:

  1. // jest.config.js
  2. setupFilesAfterEnv: ['<rootDir>/jest.setup.js']

Then, inside jest.setup.js, add the following import:

  1. // jest.setup.js
  2. import '@testing-library/jest-dom/extend-expect'

If you need to add more setup options before each test, it’s common to add them to the jest.setup.js file above.

Optional: 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. // tsconfig.json or jsconfig.json
  2. {
  3. "compilerOptions": {
  4. "baseUrl": ".",
  5. "paths": {
  6. "@/components/*": ["components/*"]
  7. }
  8. }
  9. }
  1. // jest.config.js
  2. moduleNameMapper: {
  3. '^@/components/(.*)$': '<rootDir>/components/$1',
  4. }

Creating your tests:

Add a test script to package.json

Add the Jest executable in watch mode to the package.json scripts:

  1. "scripts": {
  2. "dev": "next dev",
  3. "build": "next build",
  4. "start": "next start",
  5. "test": "jest --watch"
  6. }

jest --watch will re-run tests when a file is changed. For more Jest CLI options, please refer to the Jest Docs.

Create your first tests

Your project is now ready to run tests. Follow Jest’s convention by adding tests to the __tests__ folder in your project’s root directory.

For example, we can add a test to check if the <Home /> component successfully renders a heading:

  1. // __tests__/index.test.jsx
  2. import { render, screen } from '@testing-library/react'
  3. import Home from '../pages/index'
  4. import '@testing-library/jest-dom'
  5. describe('Home', () => {
  6. it('renders a heading', () => {
  7. render(<Home />)
  8. const heading = screen.getByRole('heading', {
  9. name: /welcome to next\.js!/i,
  10. })
  11. expect(heading).toBeInTheDocument()
  12. })
  13. })

Optionally, add a snapshot test to keep track of any unexpected changes to your <Home /> component:

  1. // __tests__/snapshot.js
  2. import { render } from '@testing-library/react'
  3. import Home from '../pages/index'
  4. it('renders homepage unchanged', () => {
  5. const { container } = render(<Home />)
  6. expect(container).toMatchSnapshot()
  7. })

Note: Test files should not be included inside the pages directory because any files inside the pages directory are considered routes.

Running your test suite

Run npm run test to run your test suite. After your tests pass or fail, you will notice a list of interactive Jest commands that will be helpful as you add more tests.

For further reading, you may find these resources helpful:

Community Packages and Examples

The Next.js community has created packages and articles you may find helpful:

For more information on what to read next, we recommend:

Test Environment VariablesLearn more about the test environment variables.