This is testing a smiple React project with Vitest and React Testing Library which includes the following Testing:
# Using npm
npm create vite@latest react-vitest-testing -- --template react
then
cd react-vitest-testing
npm install
Vitest is a lightning-fast testrunner designed to work seamlessly with Vite-based projects. It features a Jest-like API, faster startup times, and native ESM support.
Install Vitest along with React Testing Library and related packages:
npm install --save-dev vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom
- vitest: Thetest runner.
- @testing-library/react: For rendering and querying React - components in tests.
- @testing-library/jest-dom: Provides custom matchers like toBeInTheDocument().
- @testing-library/user-event: Simulates user interactions. -jsdom- to create test environments
Create a vitest.config.js file at the root of your project:
// vitest.config.js
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
setupFiles: ['./vitest.setup.js'],
css: true,
},
});
In package.json, add the test script:
"scripts": {
"test":"vitest"
}
After writing the test, it can be executed with the following command
npm run test
- Writing a simple React component and testing its rendering.
- Testing user interactions such as clicks and typing with userEvent and fireEvent.
Mock Network Requests to Test Data-Fetching Components.
When components fetch data from an API, mocking the fetch call is essential to avoid real network requests during testing.
Test custom hooks in isolation. Custom hooks can be tested in isolation to ensure that their logic works as expected.