Pular para o conteúdo

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.

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 centralizadas

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 testes
beforeAll(() => mswServer.listen({ onUnhandledRequest: "error" }));
// Reseta handlers após cada teste
afterEach(() => mswServer.resetHandlers());
// Para o server após todos os testes
afterAll(() => mswServer.close());
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();
});
});
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();
});
});

Os handlers estão organizados por domínio em handlers/:

  • auth.ts: Login, signup, logout, token refresh
  • (Adicione novos handlers conforme necessário)
// ✅ Importar de test-utils em testes Vitest
import { render, mswServer } from "@/test-utils";
import { TOKENS } from "@/test-shared"; // Shared é OK
// ❌ Importar test-utils em testes Playwright
import { mswServer } from "../../test-utils"; // ERRO!
// ❌ Importar Page Objects do Playwright aqui
import { LoginPage } from "../../e2e/pages/login"; // ERRO!
  1. Crie um arquivo em handlers/ (ex: handlers/user.ts)
  2. Exporte os handlers:
handlers/user.ts
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 });
}),
];
  1. Registre no server.ts:
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
);

Problema: Componente faz request mas MSW não intercepta.

Solução:

  1. Verifique se o handler está registrado no server.ts
  2. Confirme que o URL do handler corresponde exatamente à request
  3. Verifique se mswServer.listen() foi chamado no setup

Problema: Erro ao rodar testes Playwright.

Solução: Você está importando test-utils em testes Playwright. Use apenas test-shared em testes E2E.

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