Setting up Vitest with Next.js
Vite and React Testing Library are frequently used together for Unit Testing. This guide will show you how to setup Vitest with Next.js and write your first tests.
Good to know: Since
asyncServer Components are new to the React ecosystem, Vitest 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-vitest example to quickly get started:
1npx create-next-app@latest --example with-vitest with-vitest-app
Manual Setup
To manually set up Vitest, install vitest and the following packages as dev dependencies:
1npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react2# or3yarn add -D vitest @vitejs/plugin-react jsdom @testing-library/react @vitejs/plugin-react4# or5pnpm install -D vitest @vitejs/plugin-react jsdom @testing-library/react6# or7bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react
Create a vitest.config.ts|js file in the root of your project, and add the following options:
1import { defineConfig } from 'vitest/config'2import react from '@vitejs/plugin-react'34export default defineConfig({5plugins: [react()],6test: {7environment: 'jsdom',8},9})
For more information on configuring Vitest, please refer to the Vitest Cofiguration docs.
Then, add a test script to your package.json:
1{2"scripts": {3"dev": "next dev",4"build": "next build",5"start": "next start",6"test": "vitest"7}8}
When you run npm run test, Vitest will watch for changes in your project by default.
Creating your first Vitest Unit Test
Check that everything is working by creating a test to check if the <Page /> component successfully renders a heading:
1import Link from 'next/link'23export default function Page() {4return (5<div>6<h1>Home</h1>7<Link href="/about">About</Link>8</div>9)10}
1import { expect, test } from 'vitest'2import { render, screen } from '@testing-library/react'3import Page from '../app/page'45test('Page', () => {6render(<Page />)7expect(screen.getByRole('heading', { level: 1, name: 'Home' })).toBeDefined()8})
Good to know: The example above uses the common
__tests__convention, but test files can also be colocated inside theapprouter.
Running your tests
Then, run the following command to run your tests:
1npm run test2# or3yarn test4# or5pnpm test
Additional Resources
You may find these resources helpful: