Vitest + RTL Vitest and RTL Testing
Last updated: 2026-11-02
Vitest + RTL Vitest and RTL Testing
Vitest is a very fast test runner that shares its configuration with Vite, and React Testing Library lets you test components the way a user would: render mounts the component, getByRole queries it by semantics, userEvent simulates interactions, and the assertions target behaviour instead of implementation details. That shift is what makes the tests survive a refactoring. Because the runner reuses the Vite pipeline, the same module graph that powers the dev server powers the suite.
| Group | Data & Engineering |
|---|---|
| Kind | Tooling |
| Since | Vitest 2.x + RTL 16 |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Counter from './Counter'
describe('Counter', () => {
it('increments the number after a click', async () => {
render(<Counter />)
expect(screen.getByRole('status')).toHaveTextContent('0')
await userEvent.click(screen.getByRole('button', { name: '+1' }))
expect(screen.getByRole('status')).toHaveTextContent('1')
})
})
Returns:describe and it organise the cases; render mounts the component and returns the query handles; screen.getByRole and friends query elements by semantics; expect asserts the result.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
The Counter above changes with the buttons while the case panel below lights up one entry at a time - the RTL flow of a getByRole query plus a passing expect assertion (simulated demo).