Testing — Vitest, Playwright, Jest

Unit, Component, E2E — All Supported

Testing — Vitest, Playwright, Jest

Vitest or Jest for units and components; Playwright or Cypress for end- to-end. The Next docs document setups for each.

5 min read Level 2/5 #nextjs#testing#vitest
What you'll learn
  • Set up Vitest with `@vitejs/plugin-react`
  • Write a component test with `@testing-library/react`
  • Set up Playwright for E2E

Next does not ship a test runner — pick the one you like best. Vitest is the modern default; Playwright is the go-to for E2E.

Vitest Setup

npm i -D vitest @vitejs/plugin-react @testing-library/react @testing-library/jest-dom jsdom
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
    setupFiles: ['./vitest.setup.ts'],
  },
})

A Component Test

// components/card.test.tsx
import { render, screen } from '@testing-library/react'
import { describe, it, expect } from 'vitest'
import { Card } from './card'

describe('Card', () => {
  it('renders title', () => {
    render(<Card title="Hello" />)
    expect(screen.getByText('Hello')).toBeInTheDocument()
  })
})

Server Components that use async/await can be tested as plain async functions — call them and assert on the returned JSX.

Playwright E2E

npm i -D @playwright/test
npx playwright install
// tests/e2e/home.spec.ts
import { test, expect } from '@playwright/test'

test('home page', async ({ page }) => {
  await page.goto('/')
  await expect(page.getByRole('heading', { name: /welcome/i })).toBeVisible()
})

Configure Playwright to start next dev (or next start against a built bundle) in playwright.config.ts so tests have a server to hit.

Build & Bundle Analysis →