Show List

Mocking with React and Jest

Let's write a test case where we mock an external dependency, such as a function that fetches data from an API, and ensure that our React component behaves correctly based on the mocked data.

For this example, let's assume we have a simple component named UserList that fetches a list of users from an API and renders their names.


// UserList.js import React, { useState, useEffect } from 'react'; const UserList = () => { const [users, setUsers] = useState([]); useEffect(() => { const fetchUsers = async () => { const response = await fetch('https://jsonplaceholder.typicode.com/users'); const data = await response.json(); setUsers(data); }; fetchUsers(); }, []); return ( <div> <h1>User List</h1> <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> </div> ); }; export default UserList;

Now, let's write a test case using Jest and React Testing Library to test this component by mocking the API call.


// UserList.test.js import React from 'react'; import { render } from '@testing-library/react'; import UserList from './UserList'; // Mocking the fetch API global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve([ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' }, ]), }) ); test('renders user names from API response', async () => { const { getByText } = render(<UserList />); // Expect 'Loading...' to be displayed initially expect(getByText('User List')).toBeInTheDocument(); expect(getByText('Loading...')).toBeInTheDocument(); // Wait for the component to render with user names const johnDoeElement = await screen.findByText('John Doe'); const janeDoeElement = await screen.findByText('Jane Doe'); // Expect the user names to be displayed expect(johnDoeElement).toBeInTheDocument(); expect(janeDoeElement).toBeInTheDocument(); });

In this test case:

  1. We mock the fetch function using Jest's global.fetch = jest.fn().
  2. We provide a mock implementation that returns a resolved Promise with sample user data.
  3. We render the UserList component.
  4. We verify that "Loading..." is initially displayed while the data is being fetched.
  5. We use screen.findByText to wait for the component to render with user names.
  6. Finally, we assert that the user names are correctly displayed in the component.


This test case demonstrates how you can effectively mock external dependencies to test React components using Jest and React Testing Library.


    Leave a Comment


  • captcha text