Configuración de Vitest con Next.js

Vite y React Testing Library se usan frecuentemente juntos para pruebas unitarias (Unit Testing). Esta guía te mostrará cómo configurar Vitest con Next.js y escribir tus primeras pruebas.

Es bueno saber: Como los Componentes de Servicio async son nuevos en el ecosistema de React, Vitest actualmente no los soporta. Aunque aún puedes ejecutar pruebas unitarias para Componentes de Servicio y Cliente síncronos, recomendamos usar pruebas E2E para componentes async.

Inicio rápido

Puedes usar create-next-app con el ejemplo with-vitest de Next.js para comenzar rápidamente:

Terminal
npx create-next-app@latest --example with-vitest with-vitest-app

Configuración manual

Para configurar Vitest manualmente, instala vitest y los siguientes paquetes como dependencias de desarrollo:

Terminal
npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react
# o
yarn add -D vitest @vitejs/plugin-react jsdom @testing-library/react
# o
pnpm install -D vitest @vitejs/plugin-react jsdom @testing-library/react
# o
bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react

Crea un archivo vitest.config.ts|js en la raíz de tu proyecto y añade las siguientes opciones:

import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
  },
})
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
  },
})

Para más información sobre cómo configurar Vitest, consulta la documentación de Configuración de Vitest.

Luego, añade un script test a tu package.json:

package.json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "vitest"
  }
}

Cuando ejecutes npm run test, Vitest observará los cambios en tu proyecto por defecto.

Creando tu primera prueba unitaria con Vitest

Verifica que todo funcione creando una prueba para comprobar si el componente <Page /> renderiza correctamente un encabezado:

import Link from 'next/link'

export default function Page() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
import Link from 'next/link'

export default function Page() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
import { expect, test } from 'vitest'
import { render, screen } from '@testing-library/react'
import Page from '../app/page'

test('Page', () => {
  render(<Page />)
  expect(screen.getByRole('heading', { level: 1, name: 'Home' })).toBeDefined()
})
import { expect, test } from 'vitest'
import { render, screen } from '@testing-library/react'
import Page from '../app/page'

test('Page', () => {
  render(<Page />)
  expect(screen.getByRole('heading', { level: 1, name: 'Home' })).toBeDefined()
})

Es bueno saber: El ejemplo anterior usa la convención común __tests__, pero los archivos de prueba también pueden ubicarse dentro del enrutador app.

Ejecutando tus pruebas

Luego, ejecuta el siguiente comando para correr tus pruebas:

Terminal
npm run test
# o
yarn test
# o
pnpm test
# o
bun test

Recursos adicionales

Puedes encontrar útiles estos recursos: