Show List

Testing asynchronous operations

To write a test case for asynchronous operations using Jest and React Testing Library, let's consider a scenario where a component fetches data from an API asynchronously and renders it. We'll mock the API call and test that the component correctly renders the data it receives.

Step 1: Modify the Component to Fetch Data Asynchronously

Let's create a simple component named DataFetcher that fetches data from an API asynchronously and renders it.


import React, { useState, useEffect } from 'react'; const DataFetcher = () => { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const jsonData = await response.json(); setData(jsonData); }; fetchData(); }, []); return ( <div> {data ? ( <div> <p>Title: {data.title}</p> <p>Body: {data.body}</p> </div> ) : ( <p>Loading...</p> )} </div> ); }; export default DataFetcher;

Step 2: Write a Test Case for Asynchronous Operation

Now, let's write a test case to verify that the component correctly renders the data fetched from the API.


import React from 'react'; import { render, waitFor } from '@testing-library/react'; import DataFetcher from './DataFetcher'; test('renders fetched data', async () => { // Mock the fetch function to return a fake response global.fetch = jest.fn().mockResolvedValueOnce({ json: () => Promise.resolve({ id: 1, title: 'Test Title', body: 'Test Body' }), }); // Render the component const { getByText } = render(<DataFetcher />); // Verify that "Loading..." is displayed initially expect(getByText('Loading...')).toBeInTheDocument(); // Wait for the data to be loaded and verify that it's rendered correctly await waitFor(() => { expect(getByText('Title: Test Title')).toBeInTheDocument(); expect(getByText('Body: Test Body')).toBeInTheDocument(); }); });

Step 3: Run Tests

Run the tests using the following command:


npm test

Step 4: Review Test Results

Jest will run the test, and you should see output indicating whether the test passed or failed.

Step 5: Explore Further

You can further explore testing asynchronous operations by handling different scenarios such as error cases, loading states, and edge cases.

By following these steps, you've created a test case to validate asynchronous operations using Jest and React Testing Library. You can now continue writing tests for your React components to ensure their correctness in various scenarios.


    Leave a Comment


  • captcha text