javascript / intermediate
Snippet
Testing Asynchronous React Component Data Fetching
Asynchronous component integration tests require combining screen.findBy queries with mock resolved promises. findByRole internally polls the DOM and waits until the asynchronous state change resolves and the UI updates.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import React from 'react';import { render, screen } from '@testing-library/react';import { UserProfile } from './UserProfile';describe('UserProfile Async Component', () => {it('renders loading state and then resolves async user data', async () => {const mockFetch = jest.spyOn(global, 'fetch').mockResolvedValueOnce({ok: true,json: async () => ({ id: 101, name: 'Alice Developer' }),});render(<UserProfile userId={101} />);expect(screen.getByText(/loading/i)).toBeInTheDocument();const resolvedHeading = await screen.findByRole('heading', {name: 'Alice Developer',});expect(resolvedHeading).toBeInTheDocument();mockFetch.mockRestore();});});
react
Breakdown
1
const mockFetch = jest.spyOn(global, 'fetch').mockResolvedValueOnce({
Mocks the global fetch API to simulate an asynchronous network response without real HTTP traffic.
2
expect(screen.getByText(/loading/i)).toBeInTheDocument();
Synchronously asserts that the initial pending state is visible to the user.
3
const resolvedHeading = await screen.findByRole('heading', {
Asynchronously waits for the promise resolution and subsequent state update to render the heading element.
4
mockFetch.mockRestore();
Restores the original fetch implementation to avoid side effects across test suites.