Course contentsShow
← React
Lesson 2169 of 2,39648. End-to-End TestingFree lesson

Handling Async Operations and Network Requests

Wait for network responses with page.waitForResponse() and test loading states, error handling, and data updates.

Handling Async Operations and Network Requests

You'll learn how to wait for network responses in E2E tests and verify loading states, errors, and data updates.

In end-to-end tests, your application makes real network requests (or uses service workers like MSW). Unlike component tests where you can control timing, E2E tests need to wait for actual HTTP responses before asserting on the results.

Why This Matters

Imagine testing a dashboard that fetches user data on load. The test must wait for that network request to complete before checking if the data renders. If you assert too early, the test fails even though the app works perfectly—it just needed a moment.

Waiting for Network Responses

Playwright's page.waitForResponse() lets you wait for specific API calls to complete:

test('displays user data after fetch', async ({ page }) => {
  await page.goto('/dashboard');
  
  // Wait for the API response before proceeding
  await page.waitForResponse('**/api/user');
  
  // Now safe to assert on the data
  await expect(page.getByText('Welcome, Alice')).toBeVisible();
});

Testing the Full Async Lifecycle

Test all three states your UI cycles through:

test('handles full fetch lifecycle', async ({ page }) => {
  await page.goto('/dashboard');
  
  // 1. Loading state appears immediately
  await expect(page.getByText('Loading...')).toBeVisible();
  
  // 2. Wait for data to load
  await page.waitForResponse('**/api/posts');
  
  // 3. Content replaces loading state
  await expect(page.getByText('Loading...')).not.toBeVisible();
  await expect(page.getByRole('article')).toHaveCount(5);
});

You can also test error scenarios by configuring MSW handlers to return failure responses, then asserting error messages appear.

Key Takeaway: Use page.waitForResponse() to synchronize E2E tests with network requests, and always test loading states, successful data display, and error handling to cover the complete async experience.