Skip to content

Playwright API Mock Not Working Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Playwright API Mock Not Working Fix. We cover key concepts, practical examples, and best practices.

Your mocked API response doesn't reach the application — the app still makes real API calls or ignores the mock data.

The Problem

// WRONG — route pattern doesn't match
test('mock user API', async ({ page }) => {
  await page.route('/api/user', (route) => {
    route.fulfill({ body: JSON.stringify({ name: 'Alice' }) });
  });
  // Pattern doesn't match because URL is absolute
});

The route pattern /api/user doesn't match the full URL https://example.com/api/user. The mock is never triggered.

Step-by-Step Fix

1. Use wildcard patterns

// RIGHT — glob pattern matching
import { test, expect } from '@playwright/test';

test('mock user API', async ({ page }) => {
  await page.route('**/api/user', (route) => {
    route.fulfill({
      contentType: 'application/json',
      body: JSON.stringify({ name: 'Alice' }),
    });
  });

  await page.goto('https://example.com/profile');
  await expect(page.locator('.user-name')).toHaveText('Alice');
});

2. Mock with realistic delay

// RIGHT — simulate network delay
test('mock with realistic timing', async ({ page }) => {
  await page.route('**/api/search*', async (route) => {
    await new Promise((r) => setTimeout(r, 500));
    route.fulfill({
      body: JSON.stringify([
        { id: 1, title: 'Result 1' },
        { id: 2, title: 'Result 2' },
      ]),
    });
  });

  await page.goto('https://example.com/search');
  await page.getByRole('textbox').fill('test');
  await page.getByRole('button').click();

  await expect(page.locator('.result')).toHaveCount(2);
});

3. Mock error responses

// RIGHT — test error handling
test('mock server error', async ({ page }) => {
  await page.route('**/api/data', (route) => {
    route.fulfill({
      status: 500,
      body: 'Internal Server Error',
    });
  });

  await page.goto('https://example.com');
  await expect(page.locator('.error')).toBeVisible();
});

4. Use HAR file for recording

// RIGHT — record and replay API mocks
import { test } from '@playwright/test';

test('use HAR for mocking', async ({ page }) => {
  await page.routeFromHAR('./mocks/api.har', {
    url: '**/api/**',
    update: false,  // Set true to record
  });

  await page.goto('https://example.com');
  // Uses recorded responses from HAR file
});

Expected output:

✓ mock user API (0.9s)
✓ mock with realistic timing (1.2s)
✓ mock server error (0.7s)

Prevention Tips

  • Use **/api/... glob patterns for URL matching
  • Register mocks before page navigation
  • Mock with realistic delays to test loading states
  • Test both success and error responses
  • Use HAR files for complex mock scenarios

Common Mistakes with intercept mock

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

These mistakes appear frequently in real-world PLAYWRIGHT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does my mock not apply to iframes?

Routes apply to the page or context they're registered on. For iframes, use frame.route() on the specific frame. Global context.route() applies to all pages in the context.

Can I mock GraphQL requests?

Yes. Match the endpoint URL and parse/fulfill based on the GraphQL operation name: page.route('**/<a href="/apis/graphql/">graphql</a>', route => { const { operationName } = JSON.parse(route.request().postData()); ... }).

How do I mock responses for a specific HTTP method?

Check route.request().method() in your handler: if (route.request().method() === 'POST') { ... }. Use route.continue() to let other methods pass through.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro