💻 Exemplos: Capítulo 16: Testes no Front-End com Vitest e React Testing Library
Especialização Frontend com React & TypeScript • Demonstrações Práticas Executáveis
🎯 Contexto e Objetivo Prático
Testes unitários de componentes React com React Testing Library e Vitest, simulando interações com userEvent e asserções acessíveis.
💻 Código Fonte React 19 (TSX)
// Counter.test.tsx
import React, { useState } from "react";
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
function SimpleCounter() {
const [count, setCount] = useState(0);
return (
<div>
<p data-testid="count-display">Contagem: {count}</p>
<button onClick={() => setCount(count + 1)}>Incrementar</button>
</div>
);
}
describe("Componente <SimpleCounter />", () => {
it("deve renderizar contagem inicial em zero", () => {
render(<SimpleCounter />);
const display = screen.getByTestId("count-display");
expect(display.textContent).toBe("Contagem: 0");
});
it("deve incrementar o valor ao clicar no botão", async () => {
const user = userEvent.setup();
render(<SimpleCounter />);
const button = screen.getByRole("button", { name: /incrementar/i });
await user.click(button);
const display = screen.getByTestId("count-display");
expect(display.textContent).toBe("Contagem: 1");
});
});
🖥️ Saída de Renderização Visual e Comportamento
✓ Counter.test.tsx (2 tests) 24ms
✓ Componente <SimpleCounter /> > deve renderizar contagem inicial em zero
✓ Componente <SimpleCounter /> > deve incrementar o valor ao clicar no botão
Test Files 1 passed (1)
Tests 2 passed (2)
Duration 248ms