All challenges · Expert & Verification

Challenge 24 of 29 · Expert authoring · Verification

Inspect a Network Payload

Submit a search with a value only known at run time and capture exactly what the page sent, so the payload can be checked.

Skills you will practise

  • request bodies
  • postData
  • values known only at run time

The concept

Checking what the UI shows is only half the story. Sometimes the bug is in what the page sends: a missing field, the wrong ID, a filter that is ignored. Playwright lets you capture outgoing requests and inspect them.

page.waitForRequest() resolves with a Request object when a matching request is sent. request.postData() returns the raw body and request.postDataJSON() parses JSON or form-encoded bodies. As with responses, start waiting before the action that sends the request.

When the value you are checking is generated during the test, such as a unique search term, keep it in a variable and compare against that, rather than a hard-coded string.

The fragile version

Fragile
await page.getByRole('searchbox').fill('laptop');
await page.getByRole('button', { name: 'Find' }).click();
const req = await page.waitForRequest('**/api/search');
expect(req.postData()).toContain('laptop');

Why it breaks: The listener starts after the click, so the request may already have gone. A hard-coded term could also match cached or default data.

A robust Playwright version

Robust
const term = `laptop-${Date.now()}`;
const requestPromise = page.waitForRequest(
  r => r.url().includes('/api/search') && r.method() === 'POST'
);
await page.getByRole('searchbox').fill(term);
await page.getByRole('button', { name: 'Find' }).click();
const request = await requestPromise;
expect(request.postDataJSON()).toMatchObject({ query: term });

Listening starts first, the match is precise, and the body is checked against the run-time value.

This is a general example on a made-up page, not the challenge’s reference solution.

Common mistakes

  • Starting to wait after the triggering click.
  • Comparing raw postData() strings when the body is JSON; parse it.
  • Matching on URL alone when several methods hit the same endpoint.

FAQ

How do I get the request body in Playwright?

request.postData() for raw text, request.postDataJSON() for parsed data.

Should I use waitForRequest or page.route?

waitForRequest observes; page.route lets you change or stub the request.

Why is postDataJSON null?

The request had no body, for example a GET. Check the method.

Try it

Practise this in Challenge 24. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.

Practise this challenge free