Vitest / MSW
Utilitários específicos para testes Vitest (unitários e de integração) usando Mock Service Worker (MSW) para interceptação de requisições HTTP.
Documentação completa: Arquitetura de Testes Importante: Estes utils contêm dependências do Vitest e NÃO devem ser importados em testes Playwright. Use os Utilitários Compartilhados para código compartilhado.
Estrutura
Seção intitulada “Estrutura”test-utils/├── handlers/ # MSW handlers para interceptar APIs│ └── auth.ts # Handlers de autenticação├── middlewares/ # MSW middlewares customizados├── helpers/ # Helpers específicos do Vitest├── fixtures/ # Fixtures específicos do Vitest├── factories/ # Factories com dependências Vitest├── server.ts # Setup do MSW server└── index.ts # Exportações centralizadasSetup MSW no Vitest
Seção intitulada “Setup MSW no Vitest”O MSW server é configurado automaticamente no vitest.setup.tsx:
import { beforeAll, afterAll, afterEach } from "vitest";import { mswServer } from "./test-utils";
// Inicia o server antes de todos os testesbeforeAll(() => mswServer.listen({ onUnhandledRequest: "error" }));
// Reseta handlers após cada testeafterEach(() => mswServer.resetHandlers());
// Para o server após todos os testesafterAll(() => mswServer.close());Renderizar componente com React Query
Seção intitulada “Renderizar componente com React Query”import { render, screen } from '@/test-utils';import { MyComponent } from './my-component';
describe('MyComponent', () => { it('should fetch and display data', async () => { render(<MyComponent />);
// MSW intercepta automaticamente as requests expect(await screen.findByText('Data loaded')).toBeInTheDocument(); });});Customizar handlers por teste
Seção intitulada “Customizar handlers por teste”import { render, screen } from '@/test-utils';import { mswServer } from '@/test-utils';import { http, HttpResponse } from 'msw';
describe('MyComponent with errors', () => { it('should handle API errors', async () => { // Override handler apenas para este teste mswServer.use( http.get('/api/data', () => { return HttpResponse.json({ error: 'Failed' }, { status: 500 }); }) );
render(<MyComponent />); expect(await screen.findByText('Error occurred')).toBeInTheDocument(); });});Handlers Disponíveis
Seção intitulada “Handlers Disponíveis”Os handlers estão organizados por domínio em handlers/:
- auth.ts: Login, signup, logout, token refresh
- (Adicione novos handlers conforme necessário)
Boas Práticas
Seção intitulada “Boas Práticas”✅ Fazer
Seção intitulada “✅ Fazer”// ✅ Importar de test-utils em testes Vitestimport { render, mswServer } from "@/test-utils";import { TOKENS } from "@/test-shared"; // Shared é OK❌ NÃO Fazer
Seção intitulada “❌ NÃO Fazer”// ❌ Importar test-utils em testes Playwrightimport { mswServer } from "../../test-utils"; // ERRO!
// ❌ Importar Page Objects do Playwright aquiimport { LoginPage } from "../../e2e/pages/login"; // ERRO!Adicionar Novos Handlers
Seção intitulada “Adicionar Novos Handlers”- Crie um arquivo em
handlers/(ex:handlers/user.ts) - Exporte os handlers:
import { http, HttpResponse } from "msw";
export const userHandlers = [ http.get("/api/console/current-user", () => { return HttpResponse.json({ id: "user-123", email: "test@example.com", name: "Test User", }); }),
http.patch("/api/console/profile", async ({ request }) => { const body = await request.json(); return HttpResponse.json({ ...body, updated: true }); }),];- Registre no
server.ts:
import { setupServer } from "msw/node";import { authHandlers } from "./handlers/auth";import { userHandlers } from "./handlers/user"; // Novo
export const mswServer = setupServer( ...authHandlers, ...userHandlers, // Adiciona aqui);Troubleshooting
Seção intitulada “Troubleshooting”Requests não estão sendo interceptadas
Seção intitulada “Requests não estão sendo interceptadas”Problema: Componente faz request mas MSW não intercepta.
Solução:
- Verifique se o handler está registrado no
server.ts - Confirme que o URL do handler corresponde exatamente à request
- Verifique se
mswServer.listen()foi chamado no setup
Erro “Cannot redefine property”
Seção intitulada “Erro “Cannot redefine property””Problema: Erro ao rodar testes Playwright.
Solução: Você está importando test-utils em testes Playwright. Use apenas test-shared em testes E2E.
Handler não está sendo aplicado
Seção intitulada “Handler não está sendo aplicado”Problema: Override com mswServer.use() não funciona.
Solução:
- Use
mswServer.use()ANTES de renderizar o componente - Se ainda não funcionar, use
mswServer.resetHandlers()antes