Testing React Components with Vitest
Vitest has replaced Jest as the default test runner for modern React projects. It is faster, has native ESM support, and integrates seamlessly with Vite. Here is how to set it up and write effective component tests.
Setup with React Testing Library
Install vitest, @testing-library/react, @testing-library/jest-dom, @testing-library/user-event, and jsdom. Configure Vitest with environment: jsdom in vitest.config.ts. Create a setup file that imports @testing-library/jest-dom/vitest for extended matchers like toBeInTheDocument and toHaveTextContent.
Writing Your First Test
Render the component with render from Testing Library, find elements with screen.getByRole or screen.getByText, interact with user-event, and assert with expect. Test behavior, not implementation — ask what the user sees and does rather than what the component state is. A good test reads like a user scenario: render the form, fill in the email, click submit, verify the success message appears.
Mocking Strategies
Use vi.mock for module mocking and vi.fn for function mocking. Mock API calls with MSW (Mock Service Worker) instead of mocking fetch directly — MSW intercepts at the network level, so your tests exercise your actual data fetching code. For context providers, create a custom render function that wraps components in necessary providers.
Testing Async Behavior
Use waitFor and findBy queries for async operations. findByText waits for an element to appear, which is perfect for testing loading states and data fetching. Use waitForElementToBeRemoved to verify loading spinners disappear. Never use sleep or fixed timeouts — they make tests slow and flaky.
Common Mistakes
Do not test implementation details like state values or effect calls. Do not snapshot entire components — snapshots break on every cosmetic change and get rubber-stamp approved. Do not test third-party libraries (you did not write them). Do test user interactions, conditional rendering, error states, and accessibility (verify ARIA labels and roles). Focus your testing effort on complex logic and critical user paths.
Written by AIDToolStack Editorial
The AIDToolStack editorial team reviews developer tools, AI products, and MCP servers with hands-on testing and honest assessments. We use the tools we review every day in production.
References & Further Reading
Related Posts
Sponsor Our Newsletter
Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.
All sponsored content is clearly labeled per our editorial policy.