how testing react api project
- User
how testing react api project
- Assistant
Testing a React project that utilizes APIs is crucial to ensure that the application works as expected, especially under various conditions and edge cases. Here's a step-by-step guide to testing such projects, focusing on unit tests and integration tests.
1. Set Up Your Testing Environment
Before you start writing tests, ensure you have the necessary libraries and tools:
- Jest: A JavaScript testing framework.
- React Testing Library: A library for testing React components.
- msw (Mock Service Worker): A library for mocking API requests.
You can install these libraries using npm or yarn:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom msw2. Write Unit Tests for API Functions
If you have functions that directly interact with APIs, you should write unit tests for them. Use Jest to mock API calls.
Example:
Suppose you have an API function
fetchData:// api.js export const fetchData = async () => { const response = await fetch('/api/data'); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); return data; };You can test it as follows:
// api.test.js import { fetchData } from './api'; global.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ data: 'some data' }), }) ); test('fetchData returns data when API call is successful', async () => { const data = await fetchData(); expect(data).toEqual({ data: 'some data' }); }); test('fetchData throws an error when API call fails', async () => { global.fetch.mockImplementationOnce(() => Promise.resolve({ ok: false, }) ); await expect(fetchData()).rejects.toThrow('Network response was not ok'); });3. Write Integration Tests for React Components
Use
React Testing Libraryto render components and simulate user interactions. Combine it withmswto mock server responses.Example:
Suppose you have a component
DataComponentthat fetches and displays data:// DataComponent.js import React, { useEffect, useState } from 'react'; import { fetchData } from './api'; const DataComponent = () => { const [data, setData] = useState(null); const [error, setError] = useState(null); useEffect(() => { fetchData() .then((data) => setData(data)) .catch((error) => setError(error.message)); }, []); if (error) return <div>Error: {error}</div>; if (!data) return <div>Loading...</div>; return <div>Data: {data.data}</div>; }; export default DataComponent;And the test for it:
// DataComponent.test.js import React from 'react'; import { render, screen, waitFor } from '@testing-library/react'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; import DataComponent from './DataComponent'; const server = setupServer( rest.get('/api/data', (req, res, ctx) => { return res(ctx.json({ data: 'some data' })); }) ); beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); test('displays data when API call is successful', async () => { render(<DataComponent />); expect(screen.getByText(/Loading.../i)).toBeInTheDocument(); await waitFor(() => { expect(screen.getByText(/Data: some data/i)).toBeInTheDocument(); }); }); test('displays error when API call fails', async () => { server.use( rest.get('/api/data', (req, res, ctx) => { return res(ctx.status(500)); }) ); render(<DataComponent />); expect(screen.getByText(/Loading.../i)).toBeInTheDocument(); await waitFor(() => { expect(screen.getByText(/Error:/i)).toBeInTheDocument(); }); });4. End-to-End Tests (Optional)
For comprehensive testing, you can consider end-to-end testing with tools like Cypress. This goes beyond React and tests the entire application stack, including the backend and frontend.
5. Run Your Tests
You can run your tests using Jest:
npm testOr if you're using create-react-app, run:
npm run testSummary
- Use Jest for unit testing API functions.
- Use React Testing Library for integration testing React components.
- Mock API requests using
msw(Mock Service Worker). - Optionally, consider end-to-end testing with tools like Cypress.
By following these steps, you'll be able to ensure that your React application handles API interactions correctly and provides a robust user experience.
- User
Add and configure a test runner: Jest or Vitest. Test runner should show the test coverage. You should aim to reach at least 80% of the test coverage. Add a testing library: React Testing Library. You should add tests for the several scenarios keeping in mind that mocked data should be used instead of real API calls. Tests for the Card List component: Verify that the component renders the specified number of cards; Check that an appropriate message is displayed if no cards are present. Tests for the Card component: Ensure that the card component renders the relevant card data; Validate that clicking on a card opens a detailed card component; Check that clicking triggers an additional API call to fetch detailed information. Tests for the Detailed Card component: Check that a loading indicator is displayed while fetching data; Make sure the detailed card component correctly displays the detailed card data; Ensure that clicking the close button hides the component. Tests for the Pagination component: Make sure the component updates URL query parameter when page changes. Tests for the Search component: Verify that clicking the Search button saves the entered value to the local storage; Check that the component retrieves the value from the local storage upon mounting. Lastly, update Husky to run tests on the pre-push hook, ensuring that tests are automatically executed before any code is pushed.
- Assistant
Setting Up Jest with Test Coverage
First, install the required libraries for Jest, React Testing Library, and Husky:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom huskyNote: You can also use Vitest if you prefer, but for this example, we'll stick with Jest.
Configure Jest in
package.jsonAdd the following Jest configuration to your
package.json:"jest": { "clearMocks": true, "coverageDirectory": "coverage", "coverageThreshold": { "global": { "branches": 80, "functions": 80, "lines": 80, "statements": 80 } }, "collectCoverageFrom": [ "src/**/*.{js,jsx}", "!src/index.js", "!src/serviceWorker.js" ], "setupFilesAfterEnv": [ "@testing-library/jest-dom/extend-expect" ], "testEnvironment": "jsdom" }Setting Up Test Scenarios and Mocking Data
Directory Structure
Ensure your project has the following structure:
src/ components/ Card.js CardList.js DetailedCard.js Pagination.js Search.js __tests__/ Card.test.js CardList.test.js DetailedCard.test.js Pagination.test.js Search.test.jsTest Cases Implementation
CardList Component Tests
CardList.test.js
import React from 'react'; import { render, screen } from '@testing-library/react'; import CardList from '../components/CardList'; // Adjust the path as needed test('renders the specified number of cards', () => { const cards = ['card1', 'card2']; render(<CardList cards={cards} />); const cardElements = screen.getAllByRole('article'); // Assume each card has role="article" expect(cardElements).toHaveLength(cards.length); }); test('displays a message if no cards are present', () => { render(<CardList cards={[]} />); expect(screen.getByText(/no cards available/i)).toBeInTheDocument(); });Card Component Tests
Card.test.js
import React from 'react'; import { render, screen, fireEvent } from '@testing-library/react'; import Card from '../components/Card'; // Adjust the path as needed test('renders card data', () => { const cardData = { title: 'Title', description: 'Description' }; render(<Card card={cardData} />); expect(screen.getByText(/Title/i)).toBeInTheDocument(); expect(screen.getByText(/Description/i)).toBeInTheDocument(); }); test('clicking on card opens detailed card', () => { const cardData = { title: 'Title', description: 'Description' }; const openDetailedCard = jest.fn(); render(<Card card={cardData} onClick={openDetailedCard} />); fireEvent.click(screen.getByRole('article')); expect(openDetailedCard).toHaveBeenCalledWith(cardData); }); test('clicking triggers additional API call', async () => { // Mocking API call can be done based on the API call setup in your app // Use jest.spyOn or similar approach to test the actual API call });Detailed Card Component Tests
DetailedCard.test.js
import React from 'react'; import { render, screen } from '@testing-library/react'; import DetailedCard from '../components/DetailedCard'; // Adjust the path as needed test('displays loading indicator while fetching data', () => { render(<DetailedCard isLoading={true} />); expect(screen.getByText(/loading/i)).toBeInTheDocument(); }); test('displays detailed card data', () => { const detailedCardData = { title: 'Title', description: 'Detailed Description' }; render(<DetailedCard card={detailedCardData} isLoading={false} />); expect(screen.getByText(/Title/i)).toBeInTheDocument(); expect(screen.getByText(/Detailed Description/i)).toBeInTheDocument(); }); test('hides component when close button is clicked', () => { const onClose = jest.fn(); render(<DetailedCard onClose={onClose} />); fireEvent.click(screen.getByRole('button', { name: /close/i })); expect(onClose).toHaveBeenCalled(); });Pagination Component Tests
Pagination.test.js
import React from 'react'; import { render, screen, fireEvent } from '@testing-library/react'; import { Router } from 'react-router-dom'; import { createMemoryHistory } from 'history'; import Pagination from '../components/Pagination'; // Adjust the path as needed test('updates URL query parameter when page changes', () => { const history = createMemoryHistory(); render( <Router history={history}> <Pagination currentPage={1} totalPages={5} /> </Router> ); fireEvent.click(screen.getByText(/2/i)); // Assuming pages are clickable and numbered expect(history.location.search).toBe('?page=2'); });Search Component Tests
Search.test.js
import React from 'react'; import { render, screen, fireEvent } from '@testing-library/react'; import Search from '../components/Search'; // Adjust the path as needed test('saves search value to local storage', () => { render(<Search />); const input = screen.getByRole('textbox'); const searchButton = screen.getByRole('button', { name: /search/i }); fireEvent.change(input, { target: { value: 'test search' } }); fireEvent.click(searchButton); expect(localStorage.getItem('search')).toBe('test search'); }); test('retrieves search value from local storage on mount', () => { localStorage.setItem('search', 'stored search'); render(<Search />); const input = screen.getByRole('textbox'); expect(input.value).toBe('stored search'); });Husky Configuration
To automatically run tests before any push, use Husky: Install Husky:
npx husky-init && npm installAdd a pre-push hook to your
package.json:"husky": { "hooks": { "pre-push": "npm test" } }Running Tests and Checking Coverage
Run the tests and check the coverage with:
npm test -- --coverageEnsure the coverage report shows at least 80% coverage across your files.
By following these steps, you ensure that your React application is properly tested and that tests are run automatically before any code is pushed to the repository.