Skip to content

Fix Playwright Mock Route – Route Not Intercepted

DodaTech Updated 2026-06-24 3 min read

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

You use page.route() to mock an API call in your Playwright test. The page loads, but the request hits the real server — your mock is ignored. Or the mock returns data but the response is malformed.

Wrong ❌

test('mock API', async ({ page }) => {
  // ❌ Route registered after navigation
  await page.goto('http://localhost:3000');

  page.route('**/api/users', async (route) => {
    await route.fulfill({
      status: 200,
      body: JSON.stringify([{ id: 1, name: 'Alice' }]),
    });
  });

  // The page already fetched /api/users during navigation — too late!
});

The mock never runs because the request was made before `.route()` was called.

## Right ✅

```<a href="/programming-languages/javascript/">javascript</a>
test('mock API before navigation', async ({ page }) => {
  // ✅ Register the route BEFORE navigation
  await page.route('**/api/users', async (route) => {
    await route.fulfill({
      contentType: 'application/json',
      status: 200,
      body: JSON.stringify([{ id: 1, name: 'Alice' }]),
    });
  });

  await page.goto('http://localhost:3000');
  // The page receives the mocked response

  // Verify the data rendered
  await expect(page.getByText('Alice')).toBeVisible();
});

**Conditional mock (fulfill or continue):**

```javascript
await page.route('**/api/**', async (route) => {
  const url = route.request().url();

  if (url.includes('/users')) {
    await route.fulfill({
      status: 200,
      body: JSON.stringify({ id: 1 }),
    });
  } else {
    await route.continue();     // pass through to real server
  }
});

**Mock with delay (testing loading states):**

```<a href="/programming-languages/javascript/">javascript</a>
await page.route('**/api/users', async (route) => {
  await page.waitForTimeout(3000);    // simulate slow network
  await route.fulfill({ status: 200, body: '[]' });
});

**Verify the mock was called:**

```javascript
const requests: string[] = [];
page.on('request', (req) => requests.push(req.url()));

await page.route('**/api/users', async (route) => {
  await route.fulfill({ status: 200, body: '[]' });
});

await page.goto('http://localhost:3000');

expect(requests).toContain('http://localhost:3000/api/users');

**For POST requests:**

```<a href="/programming-languages/javascript/">javascript</a>
await page.route('**/api/login', async (route) => {
  expect(route.request().method()).toBe('POST');
  const body = route.request().postDataJSON();
  expect(body.username).toBe('admin');

  await route.fulfill({
    status: 200,
    body: JSON.stringify({ token: 'mock-token' }),
  });
});

## Root Cause

`page.route()` intercepts requests made **after** the handler is registered. If navigation happens first, the initial requests are already sent and won't be caught. Always register routes before any action that triggers the request.

## Prevention

- Register all `page.route()` calls **before** `page.goto()` or any click that triggers navigation.
- Use `page.routeFromHAR()` for recording and replaying complex API scenarios.
- Use `page.pause()` and <a href="/testing-qa/playwright/">Playwright</a> Inspector to verify routes are matching.
- Test the mock by checking `toHaveBeenCalled` patterns or inspecting the DOM.


## Common Mistakes with mock route

1. **Non-exhaustive pattern matches that compile with warnings then crash at runtime**
2. **Misunderstanding that `String` is `[Char]` with poor performance for large text operations**
3. **Using `foldl` instead of `foldl'` causing stack overflow on large lists**

These mistakes appear frequently in real-world <a href="/testing-qa/playwright/">PLAYWRIGHT</a> 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

<details style="margin-bottom:12px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden"><summary style="cursor:pointer;padding:14px 18px;font-weight:600;font-size:1.05rem;background:#f8fafc;border-bottom:1px solid #e2e8f0;color:#1e293b">**Q: Can I mock <a href="/apis/websocket/">WebSocket</a> connections?**</summary><div style="padding:14px 18px;color:#475569;line-height:1.7;background:#fff"><p>A: No — <code>page.route()</code> only intercepts HTTP(S) requests. Use <code>page.routeWebSocket()</code> (experimental) instead.</p>
</div></details><details style="margin-bottom:12px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden"><summary style="cursor:pointer;padding:14px 18px;font-weight:600;font-size:1.05rem;background:#f8fafc;border-bottom:1px solid #e2e8f0;color:#1e293b">**Q: How do I mock <a href="/apis/graphql/">GraphQL</a> requests?**</summary><div style="padding:14px 18px;color:#475569;line-height:1.7;background:#fff"><p>A: Match the endpoint URL and parse the request body to determine which query/mutation was sent.</p>
</div></details><details style="margin-bottom:12px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden"><summary style="cursor:pointer;padding:14px 18px;font-weight:600;font-size:1.05rem;background:#f8fafc;border-bottom:1px solid #e2e8f0;color:#1e293b">**Q: What's the difference between `fulfill` and `abort`?**</summary><div style="padding:14px 18px;color:#475569;line-height:1.7;background:#fff"><p>A: <code>fulfill</code> returns a mocked response; <code>abort</code> cancels the request (simulates network failure).</p>
</div></details><details style="margin-bottom:12px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden"><summary style="cursor:pointer;padding:14px 18px;font-weight:600;font-size:1.05rem;background:#f8fafc;border-bottom:1px solid #e2e8f0;color:#1e293b">**Q: Can I use `page.route` with a regex?**</summary><div style="padding:14px 18px;color:#475569;line-height:1.7;background:#fff"><p>A: Yes — <code>page.route(/\/api\/users\/\d+/, handler)</code>.</p>
</div></details>

---

*Request mocking is covered in the [DodaTech <a href="/testing-qa/playwright/">Playwright</a> Mocking course](https://dodatech.com/courses/<a href="/testing-qa/playwright/">playwright</a>).*

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro