Sure, here's a comprehensive guide to setting up Jest or Vitest with React Testing Library in a Vite React TypeScript project, along with adding relevant tests.
1. Setting Up the Project
1.1. Install Dependencies
First, let's install the necessary packages:
# Vite, React, and TypeScript setup
npm create vite@latest my-vite-app -- --template react-ts
cd my-vite-app
npm install
# Testing dependencies
npm install --save-dev jest @types/jest ts-jest jest-environment-jsdom
npm install --save-dev @testing-library/react @testing-library/jest-dom
# Additional libraries (if using Jest)
npm install --save-dev babel-jest @babel/preset-env @babel/preset-react
1.2. Configure Jest
Create a jest.config.js file in the root of your project:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['./jest.setup.ts'],
collectCoverage: true,
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
};
Create a jest.setup.ts file in the root of your project:
import '@testing-library/jest-dom';
1.3. Add Babel Configuration (if using Jest)
Create a .babelrc file:
{
"presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"]
}
2. Writing Tests
2.1. Card List Component Tests
// src/tests/CardList.test.tsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import CardList from '../components/CardList'; // Adjust the import
import '@testing-library/jest-dom/extend-expect';
describe('Card List', () => {
test('renders the specified number of cards', () => {
const mockCards = [{ id: 1 }, { id: 2 }, { id: 3 }];
render(<CardList cards={mockCards} />);
expect(screen.getAllByTestId('card')).toHaveLength(3);
});
test('displays a message if no cards are present', () => {
render(<CardList cards={[]} />);
expect(screen.getByText('No cards available')).toBeInTheDocument();
});
});
2.2. Card Component Tests
// src/tests/Card.test.tsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Card from '../components/Card'; // Adjust the import
import '@testing-library/jest-dom/extend-expect';
describe('Card Component', () => {
test('renders the card data', () => {
const cardData = { title: 'Card Title', description: 'Card Description' };
render(<Card card={cardData} />);
expect(screen.getByText('Card Title')).toBeInTheDocument();
expect(screen.getByText('Card Description')).toBeInTheDocument();
});
test('clicking the card opens detailed card component', () => {
const cardData = { id: 1, title: 'Card Title' };
render(<Card card={cardData} />);
fireEvent.click(screen.getByTestId('card'));
expect(screen.getByTestId('detailed-card')).toBeInTheDocument();
});
});
2.3. Detailed Card Component Tests
// src/tests/DetailedCard.test.tsx
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import DetailedCard from '../components/DetailedCard'; // Adjust the import
import '@testing-library/jest-dom/extend-expect';
import fetch from 'jest-fetch-mock';
jest.mock('jest-fetch-mock');
beforeEach(() => {
fetch.resetMocks();
});
describe('Detailed Card Component', () => {
test('displays a loading indicator while fetching data', () => {
fetch.mockResponseOnce(JSON.stringify({ title: 'Detailed Card' }));
render(<DetailedCard id={1} />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
test('displays detailed card data once fetched', async () => {
fetch.mockResponseOnce(JSON.stringify({ title: 'Detailed Card' }));
render(<DetailedCard id={1} />);
await waitFor(() => expect(screen.getByText('Detailed Card')).toBeInTheDocument());
});
});
2.4. Pagination Component Tests
// src/tests/Pagination.test.tsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { useHistory, useLocation } from 'react-router-dom';
import Pagination from '../components/Pagination'; // Adjust the import
import '@testing-library/jest-dom/extend-expect';
jest.mock('react-router-dom', () => ({
useHistory: jest.fn(),
useLocation: jest.fn(),
}));
describe('Pagination Component', () => {
test('updates URL query parameter when page changes', () => {
const push = jest.fn();
useHistory.mockReturnValueOnce({ push });
useLocation.mockReturnValueOnce({ search: '' });
render(<Pagination totalPages={10} />);
fireEvent.click(screen.getByText('2'));
expect(push).toHaveBeenCalledWith('?page=2');
});
});
2.5. Search Component Tests
// src/tests/Search.test.tsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Search from '../components/Search'; // Adjust the import
import '@testing-library/jest-dom/extend-expect';
describe('Search Component', () => {
test('saves value to local storage on search', () => {
Storage.prototype.setItem = jest.fn();
render(<Search />);
fireEvent.change(screen.getByPlaceholderText('Search...'), { target: { value: 'test value' } });
fireEvent.click(screen.getByText('Search'));
expect(localStorage.setItem).toHaveBeenCalledWith('search', 'test value');
});
test('retrieves value from local storage on mount', () => {
Storage.prototype.getItem = jest.fn(() => 'test value');
render(<Search />);
expect(screen.getByPlaceholderText('Search...')).toHaveValue('test value');
});
});
3. Configuring Husky
3.1. Install Husky
npm install husky --save-dev
npx husky install
3.2. Add pre-push hook
npx husky add .husky/pre-push "npm test"
This will ensure all tests are run before pushing code to the repository.
4. Run Tests
You can now run tests using:
npm test
5. View Test Coverage
To view test coverage, run:
npm test -- --coverage
This setup will run your tests and provide a coverage report, aiming for at least 80% coverage.
Note on Vitest
If you prefer using Vitest instead of Jest:
# Install Vitest and React Testing Library
npm install --save-dev vitest @testing-library/react @testing-library/jest-dom
# Configure Vitest in vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: ['./vitest.setup.ts'],
coverage: {
provider: 'istanbul',
all: true,
statements: 80,
branches: 80,
functions: 80,
lines: 80,
},
}
});
// Create a vitest.setup.ts file
import '@testing-library/jest-dom';
// Run Vitest tests
npx vitest
Follow the remaining test writing and setup steps similarly as explained above.