Cursor rules for testing React components with Vitest, React Testing Library and user-event, including setup, query priority, mocking and async patterns.
.cursor/rules/react-testing-with-vitest.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for testing React components with Vitest, React Testing Library and user-event, including setup, query priority, mocking and async patterns."
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing tests for React components with Vitest and React Testing Library.
## Testing approach
- Test behaviour from the user's perspective, not implementation details.
- Prefer tests that render a component with its real children and providers; mock only the boundaries (network, router, browser APIs that jsdom lacks).
- Use snapshot tests sparingly and never as the only assertion.
## Setup
- Run component tests in a DOM environment (`test.environment: 'jsdom'` or `'happy-dom'` in the Vitest config, or per file with a `// @vitest-environment jsdom` comment).
- Register the jest-dom matchers in a setup file (`import '@testing-library/jest-dom/vitest'`) so `toBeInTheDocument` and similar matchers exist and are typed.
## Test structure
```tsx
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoginForm } from './LoginForm';
describe('LoginForm', () => {
it('submits the entered credentials', async () => {
const onSubmit = vi.fn();
const user = userEvent.setup();
render(<LoginForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText(/email/i), 'test@example.com');
await user.type(screen.getByLabelText(/password/i), 'password123');
await user.click(screen.getByRole('button', { name: /sign in/i }));
expect(onSubmit).toHaveBeenCalledWith({
email: 'test@example.com',
password: 'password123',
});
});
it('shows validation errors for empty fields', async () => {
const user = userEvent.setup();
render(<LoginForm onSubmit={vi.fn()} />);
await user.click(screen.getByRole('button', { name: /sign in/i }));
expect(await screen.findByText(/email is required/i)).toBeInTheDocument();
expect(screen.getByText(/password is required/i)).toBeInTheDocument();
});
});
```
If `onSubmit` is called after an asynchronous step (for example async validation), wrap the assertion in `await waitFor(...)` instead.
## Query priority
1. `getByRole`
2. `getByLabelText`
3. `getByPlaceholderText`
4. `getByText`
5. `getByDisplayValue`
6. `getByAltText`, `getByTitle`
7. `getByTestId` (last resort)
## Mocking
```ts
import { afterEach, vi } from 'vitest';
// Module mocks are hoisted above imports
vi.mock('@/lib/api', () => ({ fetchUser: vi.fn() }));
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => '/test',
}));
// Stub globals through Vitest so they are restored between tests
vi.stubGlobal('fetch', vi.fn(async () => Response.json({ data: 'test' })));
afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});
```
- For components that fetch data, prefer MSW handlers over stubbing `fetch`, so the real request code runs.
- Use `vi.mocked(fn)` to get typed access to a mocked import.
## Async testing
- Use `findBy*` queries for elements that appear after async work, and `waitFor` for assertions that are not about a single element appearing.
- Do not raise timeouts to hide flaky tests; find the missing `await`, unresolved request handler or timer instead (`vi.useFakeTimers()` for time-based logic).
- Testing Library unmounts rendered components after each test automatically when the runner exposes globals or you call `cleanup` in `afterEach`; restore stubs and mocks there as well.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
testing
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Adding tests for a LoginForm that validates on submit and calls onSubmit({ email, password }). The current test file assigns global.fetch directly and uses a Mock type that is never imported.
Follow the React Testing with Vitest rule. Write LoginForm.test.tsx for src/components/LoginForm.tsx; Vitest config is vitest.config.ts with a setup file at test/setup.ts.
A test file that uses userEvent.setup(), role/label queries, findBy for the validation message, vi.stubGlobal (with vi.unstubAllGlobals in afterEach) or MSW instead of assigning global.fetch, and a setup file that imports @testing-library/jest-dom/vitest.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/react-testing-with-vitest.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "React Testing with Vitest project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing tests for React components with Vitest and React Testing Library.
## Testing approach
- Test behaviour from the user's perspective, not implementation details.
- Prefer tests that render a component with its real children and providers; mock only the boundaries (network, router, browser APIs that jsdom lacks).
- Use snapshot tests sparingly and never as the only assertion.
## Setup
- Run component tests in a DOM environment (`test.environment: 'jsdom'` or `'happy-dom'` in the Vitest config, or per file with a `// @vitest-environment jsdom` comment).
- Register the jest-dom matchers in a setup file (`import '@testing-library/jest-dom/vitest'`) so `toBeInTheDocument` and similar matchers exist and are typed.
## Test structure
```tsx
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoginForm } from './LoginForm';
describe('LoginForm', () => {
it('submits the entered credentials', async () => {
const onSubmit = vi.fn();
const user = userEvent.setup();
render(<LoginForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText(/email/i), 'test@example.com');
await user.type(screen.getByLabelText(/password/i), 'password123');
await user.click(screen.getByRole('button', { name: /sign in/i }));
expect(onSubmit).toHaveBeenCalledWith({
email: 'test@example.com',
password: 'password123',
});
});
it('shows validation errors for empty fields', async () => {
const user = userEvent.setup();
render(<LoginForm onSubmit={vi.fn()} />);
await user.click(screen.getByRole('button', { name: /sign in/i }));
expect(await screen.findByText(/email is required/i)).toBeInTheDocument();
expect(screen.getByText(/password is required/i)).toBeInTheDocument();
});
});
```
If `onSubmit` is called after an asynchronous step (for example async validation), wrap the assertion in `await waitFor(...)` instead.
## Query priority
1. `getByRole`
2. `getByLabelText`
3. `getByPlaceholderText`
4. `getByText`
5. `getByDisplayValue`
6. `getByAltText`, `getByTitle`
7. `getByTestId` (last resort)
## Mocking
```ts
import { afterEach, vi } from 'vitest';
// Module mocks are hoisted above imports
vi.mock('@/lib/api', () => ({ fetchUser: vi.fn() }));
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => '/test',
}));
// Stub globals through Vitest so they are restored between tests
vi.stubGlobal('fetch', vi.fn(async () => Response.json({ data: 'test' })));
afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});
```
- For components that fetch data, prefer MSW handlers over stubbing `fetch`, so the real request code runs.
- Use `vi.mocked(fn)` to get typed access to a mocked import.
## Async testing
- Use `findBy*` queries for elements that appear after async work, and `waitFor` for assertions that are not about a single element appearing.
- Do not raise timeouts to hide flaky tests; find the missing `await`, unresolved request handler or timer instead (`vi.useFakeTimers()` for time-based logic).
- Testing Library unmounts rendered components after each test automatically when the runner exposes globals or you call `cleanup` in `afterEach`; restore stubs and mocks there as well.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.