Unit Testing Setup Guide (Vitest + React Testing Library)
1. Install Dependencies (Using Terminal Commands)
Run the following command in your terminal to install the necessary testing libraries as
development dependencies:
npm install -D vitest @testing-library/react @testing-library/jest-dom
@testing-library/user-event jsdom
2. Configure Vite ([Link])
Update your [Link] to include the test configuration inside defineConfig:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/[Link]',
},
})
3. Create Setup File (src/[Link])
Create a file named [Link] inside the src folder and add:
import '@testing-library/jest-dom';
4. Add Test Script ([Link])
Add the following test script inside the scripts section of [Link]:
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --
max-warnings 0",
"preview": "vite preview",
"test": "vitest"
}
5. Create Your First Test (src/[Link])
Create a test file for your component (example: [Link]):
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import App from './App';
describe('App', () => {
it('renders correctly', () => {
render(<App />);
// Example assertion:
// expect([Link]('Hello World')).toBeInTheDocument();
});
});
6. Run Tests
Run the tests using:
npm test
Alternative Method: Using Antigravity Prompt (Automatic Setup)
Instead of manually configuring everything, you can use the following prompt in Antigravity
to automate the entire setup:
Please set up a complete unit testing environment for this React & Vite
project using Vitest and React Testing Library.
I need you to handle the entire setup:
Install dependencies: Install vitest, jsdom, @testing-library/react,
@testing-library/jest-dom, and @testing-library/user-event.
Configure Vite: Update [Link] to enable test globals, set the
environment to jsdom, and point to a setup file.
Setup File: Create src/[Link] and import @testing-library/jest-
dom to enable custom matchers.
Scripts: Add a "test": "vitest" script to my [Link].
Generate Tests: Once configured, please read my existing components in
src/components and generate comprehensive unit test files (e.g.,
[Link]) for them, ensuring they verify correct rendering and
basic interactions.