Introducción/Guías/Pruebas/Vitest

Cómo configurar Vitest con Next.js

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

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

Inicio rápido

Puede 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, instale vitest y los siguientes paquetes como dependencias de desarrollo:

Terminal
# Usando TypeScript
npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom vite-tsconfig-paths
# Usando JavaScript
npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom

Cree un archivo vitest.config.mts|js en la raíz de su proyecto y agregue las siguientes opciones:

import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [tsconfigPaths(), 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 la configuración de Vitest, consulte la documentación de Configuración de Vitest.

Luego, agregue un script test a su package.json:

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

Cuando ejecute npm run test, Vitest observará los cambios en su proyecto por defecto.

Creando su primera prueba unitaria con Vitest

Verifique 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 saberlo: El ejemplo anterior usa la convención común __tests__, pero los archivos de prueba también pueden ubicarse junto a los componentes dentro del enrutador app.

Ejecutando sus pruebas

Luego, ejecute el siguiente comando para correr sus pruebas:

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

Recursos adicionales

Puede encontrar útiles estos recursos: