102 / 139 · 13 Browser Automation with Playwright · Network Mocking and API Testing← prev⊞ allnext →☰ Read as one page
11.6Network Mocking Patterns
| Pattern | Use Case |
|---|---|
| Full mock | Test UI in isolation from backend |
| Error simulation | Verify error handling (500, 403, timeout) |
| Slow response | Test loading states and spinners |
| Modified response | Inject feature flags or test-specific data |
| Abort requests | Block analytics, images, third-party scripts |
| Record & replay | Snapshot real responses for deterministic tests |
Simulating Slow Responses
test('shows loading spinner for slow API', async ({ page }) => {
await page.route('**/api/reports', async (route) => {
await new Promise((resolve) => setTimeout(resolve, 3000));
await route.fulfill({ status: 200, body: '[]' });
});
await page.goto('/reports');
await expect(page.getByTestId('spinner')).toBeVisible();
await expect(page.getByTestId('spinner')).not.toBeVisible({ timeout: 5000 });
});