Test React Components with Vitest and Testing Library
Intermediate15 minTrending
Set up and write component tests using Vitest and React Testing Library with user-centric queries and assertions.
Prerequisites
- -React or Next.js project
- -Node.js 18+
- -Familiarity with React components
Steps
1
Install Vitest and React Testing Library
Add the testing dependencies including jsdom for browser environment simulation.
$ pnpm add -D vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom @vitejs/plugin-react
2
Create the Vitest config
Add a vitest.config.ts with jsdom environment and React plugin.
$ cat > vitest.config.ts << 'EOF'
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['./src/test/setup.ts'],
css: true,
},
});
EOF
3
Create the test setup file
Import jest-dom matchers so you can use toBeInTheDocument() and similar assertions.
$ mkdir -p src/test && echo "import '@testing-library/jest-dom/vitest';" > src/test/setup.ts
4
Write a component test
Create a test file that renders a component and asserts on its output.
$ cat > src/components/__tests__/Button.test.tsx << 'EOF'
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi } from 'vitest';
import { Button } from '../Button';
describe('Button', () => {
it('renders with text and handles click', async () => {
const onClick = vi.fn();
render(<Button onClick={onClick}>Click me</Button>);
await userEvent.click(screen.getByRole('button', { name: /click me/i }));
expect(onClick).toHaveBeenCalledOnce();
});
});
EOF
Always query by role or accessible name instead of test IDs for more resilient tests.
5
Run the tests
Execute the test suite with Vitest in watch mode.
$ pnpm vitest
Use 'pnpm vitest run' for a single CI-friendly run without watch mode.
Full Script
FAQ
Discussion
Loading comments...