Skip to content

Mezekr/react-vitest-testing

Repository files navigation

Testing in React using Vitest and React Testing Library

This is testing a smiple React project with Vitest and React Testing Library which includes the following Testing:

1. Setting up a React app with Vite.

    # Using npm
    npm create vite@latest react-vitest-testing -- --template react
then
    cd react-vitest-testing
    npm install

2. Configuring Vitest and React Testing Library.

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.

Step 2.1. Install Testing Dependencies

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

Step 2.2. Configure Vitest

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,
	},
});

Step 2.3. Update Test Scripts

In package.json, add the test script:

"scripts": {
  "test":"vitest"
}

Step 2.5.Run test

After writing the test, it can be executed with the following command

npm run test

Basic UI Testing

  • Writing a simple React component and testing its rendering.

4. Testing User Events

  • Testing user interactions such as clicks and typing with userEvent and fireEvent.

5. Testing Components that Fetch Data

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.

6. Testing Custom Hooks

Test custom hooks in isolation. Custom hooks can be tested in isolation to ensure that their logic works as expected.

About

Using Vitest and the React Testing Library to test a simple React project.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published