Playwright network mocking and API testing

9 min read · TypeScript · 6 linked exercises

Some of the most important states of an app are the hardest to reach through the UI: a server error, an empty list, a slow response, a payment provider that's down. Playwright can intercept every request the page makes, so your test decides what the server answers.

This guide covers mocking with page.route(), checking what the page sent and received, and testing the API directly with the request fixture. At the end, it combines API and UI in one fast test.

Mock a response with page.route()

page.route() registers a handler for every request whose URL matches. Register it before the request happens, usually before page.goto() or before the click that loads data:

await page.route('**/api/products', (route) =>
  route.fulfill({
    json: { products: [{ id: 99, name: 'Mock Product', price: 1 }] },
  }),
);

await page.goto('/network/mocking');
await expect(page.getByText('Mock Product')).toBeVisible();

A handler has four main answers:

  • route.fulfill() answers with your own status, headers and body.
  • route.abort() fails the request, as if the network dropped.
  • route.continue() sends the request on to the server, optionally with changed headers or body.
  • route.fetch() gets the real response, so you can change it before fulfilling.
Practise it
  • Network MockingAdvancedMock products, errors, delays and an extra search result.

Errors, slow responses and retries

// A server error
await page.route('**/api/products', (route) =>
  route.fulfill({ status: 500, json: { error: 'Internal error' } }),
);

// The network fails entirely
await page.route('**/api/products', (route) => route.abort());

// The real response, two seconds late, to test the loading state
await page.route('**/api/products', async (route) => {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  await route.continue();
});

// Fail only the first request, so the Retry button gets the real data
await page.route('**/api/notifications', (route) =>
  route.fulfill({ status: 503 }), { times: 1 });

Mock only what the test is about. Everything you mock is something the test no longer checks. Mock the edge case and let the rest of the app talk to the real backend.

Practise it
  • Network MockingAdvancedMake notifications fail once, then let Retry succeed.
  • AutocompleteIntermediateMock the city search API with an error and recover.
  • Checkout Edge CasesAdvancedMock a payment outage and assert the customer can try again.

URL patterns that match what you mean

A glob must match the whole URL, query string included. So '**/api/products' doesn't match /api/products?q=phone. For those, use a glob with a wildcard, a regular expression or a function:

await page.route('**/api/products?*', handler);
await page.route(/\/api\/products\?.*q=phone/, handler);
await page.route((url) => url.searchParams.get('q') === 'phone', handler);

When several routes match, the one registered last runs first. Inside a handler, route.fallback() passes the request on to the next matching route instead of to the network.

Practise it
  • Network MockingAdvancedMock only searches for "phone", and let other searches through.

Check what the page sent

Sometimes the screen looks right but the request was wrong: a missing field, a wrong ID, two requests instead of one. Wait for the request or response, and assert on it:

const requestPromise = page.waitForRequest(
  (request) => request.url().endsWith('/api/users') && request.method() === 'POST',
);
await page.getByRole('button', { name: 'Create user' }).click();

const request = await requestPromise;
expect(request.postDataJSON()).toEqual({ firstName: 'Ada', lastName: 'Lovelace', role: 'User' });

Start waiting before the click, so a fast request can't slip past. To count requests, for example to check that a search box debounces, listen with page.on('request') and count the ones that match.

Practise it
  • API PlaygroundIntermediateAssert the exact JSON body the page sent, and the 404 and 400 responses.
  • AutocompleteIntermediateCount the requests a debounced search sends.

Test the API directly

The request fixture sends HTTP requests without a browser. It uses the baseURL from your config, and is much faster than going through the UI:

test('creates a user', async ({ request }) => {
  const response = await request.post('/api/users', {
    data: { firstName: 'Ada', lastName: `Lovelace ${Date.now()}`, role: 'User' },
  });

  expect(response.status()).toBe(201);
  expect(await response.json()).toEqual(
    expect.objectContaining({ firstName: 'Ada' }),
  );
});

Tests run in parallel, often against shared data. Give everything a test creates a unique name, and delete it at the end, so tests never depend on each other.

Practise it
  • API TestingAdvancedGET, POST, PUT, PATCH and DELETE against the practice API, with auth.

API and UI in one test

The fastest end-to-end tests set up their data through the API and use the browser only for the part they check. Register an account and place an order with request, then open the order page signed in, and assert what the customer sees.

It works the other way too. Do something in the UI, then read it back through the API to check that the server stored what the screen shows.

Practise it
  • UI + API TogetherAdvancedSet up orders through the API, check them in the Mini Shop UI.

Exercises in this guide

More guides