Capítulo 330 de 456

Vitest

Core Idea

Setup de Vitest + React Testing Library para Unit Testing no Next.js, como alternativa mais rápida ao Jest.

Key Concepts

  • @vitejs/plugin-react: plugin necessário para Vitest processar JSX/React.
  • vite-tsconfig-paths: resolve os path aliases do tsconfig.json dentro do Vitest (só necessário em projetos TypeScript).
  • defineConfig de vitest/config: função de config, com test.environment: 'jsdom' para simular DOM.
  • Watch mode por padrão: vitest/npm run test fica observando mudanças automaticamente.

Code Examples

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' },
})
  • O que demonstra: config mínima de Vitest com suporte a JSX e path aliases.
import { expect, test } from 'vitest'
import { render, screen } from '@testing-library/react'
import Page from '../pages/index'

test('Page', () => {
  render(<Page />)
  expect(screen.getByRole('heading', { level: 1, name: 'Home' })).toBeDefined()
})
  • O que demonstra: teste unitário de render de heading, equivalente ao padrão usado com Jest.

Anti-patterns

  • Testar Server Components async com Vitest: não suportado; usar E2E (Cypress/Playwright) para esse caso.

Key Takeaways

  1. Vitest exige configuração explícita de @vitejs/plugin-react e environment: 'jsdom', diferente do next/jest que já vem pronto.
  2. Roda em watch mode por padrão ao chamar npm run test.
  3. API de asserção é praticamente intercambiável com Jest (test, expect, render, screen).

Connects To

  • Jest: alternativa com integração nativa via next/jest, mais "batteries included".
  • Playwright / Cypress: cobrem E2E e async Server Components, fora do escopo do Vitest.