πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 69 of 100
Network
Advanced

What are HAR files and how are they used in Playwright?

The Answer

HAR (HTTP Archive) is a JSON format that records all network activity. Playwright can record a HAR file and later replay it, serving all recorded responses without hitting the real server.

Deep Dive Explanation

HAR-based testing is excellent for: 1) Creating offline/hermetic tests that never hit real APIs. 2) Refreshing mock data easily (just run with `update: true`). 3) Testing complex sequences of API calls without writing individual `route.fulfill()` handlers.

example.spec.ts
// STEP 1: Record HAR file
test('record har', async ({ page, context }) => {
  await context.routeFromHAR('tests/fixtures/api.har', { update: true });
  await page.goto('/app'); // Real network calls are recorded
  // HAR file is written when context closes
});

// STEP 2: Replay HAR file in tests (offline)
test('use recorded har', async ({ page, context }) => {
  await context.routeFromHAR('tests/fixtures/api.har', {
    update: false,    // Replay mode - no real network calls
    notFound: 'abort', // Abort requests not in the HAR
  });
  await page.goto('/app');
  // All responses come from HAR file
  await expect(page.getByText('Dashboard')).toBeVisible();
});