Everything a repo needs before the first test. Open this when setting up a project, adding Browser Mode, or fixing "works locally, fails in CI".
Sources: https://vitest.dev/guide/browser/ · https://mswjs.io/docs/integrations/node · https://testing-library.com/docs/react-testing-library/setup
Packages
npm i -D vitest @vitest/coverage-v8 jsdom \
@testing-library/react @testing-library/dom @testing-library/jest-dom @testing-library/user-event \
msw vitest-axe
@testing-library/react 16 declares @testing-library/dom as a peer dependency — installs that omit it fail at import time with "Cannot find module @testing-library/dom".
1. vitest.config.ts (jsdom, the default)
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
plugins: [react(), tsconfigPaths()],
test: {
environment: 'jsdom',
globals: true, // so RTL auto-cleanup hooks into afterEach
setupFiles: ['./src/test/setup.ts'],
css: false, // CSS never changes an assertion in jsdom
restoreMocks: true,
coverage: {
provider: 'v8',
include: ['src/features/**', 'src/shared/**'],
thresholds: { statements: 70, branches: 60 },
},
},
});
2. src/test/setup.ts
import '@testing-library/jest-dom/vitest';
import { afterAll, afterEach, beforeAll } from 'vitest';
import { server } from './msw/server';
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
No cleanup() call: React Testing Library registers it automatically when a global afterEach exists. Adding it by hand is a signal the author did not check, and it hides double-cleanup bugs.
3. src/test/render.tsx
import type { ReactElement, ReactNode } from 'react';
import { render, type RenderOptions } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from '@/shared/theme';
export function renderWithProviders(ui: ReactElement, options?: Omit<RenderOptions, 'wrapper'>) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } },
});
function Wrapper({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider>{children}</ThemeProvider>
</QueryClientProvider>
);
}
return { queryClient, ...render(ui, { wrapper: Wrapper, ...options }) };
}
retry: false is mandatory: with retries on, an error-path test waits for three failed attempts and then times out.
4. MSW server and handlers
// src/test/msw/server.ts
import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);
// src/test/msw/handlers/orders.ts
import { http, HttpResponse } from 'msw';
export const orderHandlers = [
http.get('/api/orders', () => HttpResponse.json({ items: [{ id: '1', total: 10 }] })),
http.post('/api/orders', async ({ request }) => {
const body = (await request.json()) as { email?: string };
if (!body.email) return HttpResponse.json({ message: 'email required' }, { status: 422 });
return HttpResponse.json({ id: '42' }, { status: 201 });
}),
];
Keep handlers shaped exactly like the real API — a handler that returns a convenient shape hides the bug it was meant to catch. The same handlers feed Storybook (msw-storybook-addon) and, where useful, Playwright.
5. Browser Mode (real browser, real layout)
Switch when a test depends on layout, focus order, IntersectionObserver, pointer events or scrolling — things jsdom does not implement.
npm i -D @vitest/browser-playwright vitest-browser-react playwright
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import { playwright } from '@vitest/browser-playwright';
export default defineConfig({
plugins: [react()],
test: {
setupFiles: ['./src/test/setup.ts'],
browser: {
enabled: true,
provider: playwright(),
headless: true,
instances: [{ browser: 'chromium' }],
},
},
});
import { render } from 'vitest-browser-react';
import { expect, it } from 'vitest';
it('scrolls the selected row into view', async () => {
const screen = render(<OrderTable selectedId="42" />);
await expect.element(screen.getByRole('row', { name: /order 42/i })).toBeVisible();
});
Browser Mode locators auto-retry, so there is no findBy*/waitFor split; assert with expect.element(...). Keep the bulk of the suite in jsdom for speed and put only layout-dependent tests here — a second Vitest project (projects in the config) can run both in one command.
6. Coverage and CI
lint + tsc --noEmit
→ vitest run --coverage (sharded)
→ build
→ vitest run --project=storybook (Storybook via @storybook/addon-vitest)
→ playwright test --shard=i/n (against the production build)
- Gate on: type errors, lint errors, failing tests, accessibility violations, and coverage of changed files (
vitest run --changed origin/main --coverage). Do not gate on a global percentage that must always climb. TZ=UTCand a fixed viewport in CI; a timezone-dependent assertion is the classic "only fails in CI".- Shard both Vitest and Playwright; keep total wall time under ten minutes or people stop running it.