日本語

“Playwright waitForRequest: Check the Request Sent When a Button Is Clicked”

​​Playwright​E2E Testing,TypeScript

To check in an E2E test that the page sent the correct values to the API when a form's "Register" or "Save" button was clicked, use Playwright's page.waitForRequest(). Start waiting before the click, then take the captured request and inspect its body (postDataJSON()) and headers (headers()).

I ran a test in a test environment that checks the contents of the request actually sent to the server. I also show how it fails when waiting starts in the wrong order and when it captures a different request.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.5, @playwright/test 1.63.0 (Chromium 158.0.8127.36, headless), and TypeScript 5.9.3. The page was served by a small server built with Node.js's http module (listening on port 3000), and this server returned the responses to the API calls. I did not test Firefox or WebKit, Windows or macOS, or multipart/form-data for file uploads.

The page I tested: a Register button that sends one GET and one POST

The page has input fields for a cat's name and age, and a "Register" button. When the button is pressed, it first sends GET /api/cats?name=… to check whether a cat with the same name already exists. If not, it sends the name and age as JSON to POST /api/cats. The following code is the part of the page's HTML that handles the button.

js
document.getElementById('add').addEventListener('click', async () => {
  const name = document.getElementById('name').value;
  const age = Number(document.getElementById('age').value);
  // First, check with GET whether a cat with the same name already exists
  const check = await fetch(`/api/cats?name=${encodeURIComponent(name)}`).then((r) => r.json());
  if (check.exists) {
    document.getElementById('status').textContent = 'もう登録されています';
    return;
  }
  // Then send the registration data with POST
  const res = await fetch('/api/cats', {
    method: 'POST',
    headers: { 'content-type': 'application/json', 'x-client': 'web' },
    body: JSON.stringify({ name, age }),
  });
  const cat = await res.json();
  document.getElementById('status').textContent = `${cat.name}を登録しました(ID ${cat.id})`;
});

When I entered "Tama" as the name and "3" as the age and pressed the button, I recorded every request the page sent with page.on('request'). There were two:

text
GET http://localhost:3000/api/cats?name=%E3%81%9F%E3%81%BE
POST http://localhost:3000/api/cats

The test needs to check the body sent in the second request, the POST. The configuration file (playwright.config.ts) sets baseURL: 'http://localhost:3000' under use.

Start waiting with waitForRequest() before the click

The test that checks the POST contents is written as follows. The key point is to call page.waitForRequest() without await, store the Promise in a variable, and only then press the button. The example in the page.waitForRequest() API reference is also written in this order.

ts
import { test, expect } from '@playwright/test';

test('登録ボタンで、名前と年齢を POST で送る', async ({ page }) => {
  await page.goto('/');
  await page.getByLabel('名前').fill('たま');
  await page.getByLabel('年齢').fill('3');

  // Start waiting before the click
  const requestPromise = page.waitForRequest(
    (req) => req.url().endsWith('/api/cats') && req.method() === 'POST',
  );
  await page.getByRole('button', { name: '登録' }).click();
  const request = await requestPromise;

  console.log('url:', request.url());
  console.log('method:', request.method());
  console.log('headers:', request.headers());
  console.log('postData:', request.postData());
  console.log('postDataJSON:', request.postDataJSON());

  expect(request.method()).toBe('POST');
  expect(request.headers()['content-type']).toBe('application/json');
  expect(request.headers()['x-client']).toBe('web');
  expect(request.postDataJSON()).toEqual({ name: 'たま', age: 3 });

  // The response to the request sent can also be reached from the same object
  const response = await request.response();
  console.log('status:', response?.status());
  console.log('response json:', await response?.json());
  expect(response?.status()).toBe(201);
  await expect(page.getByText('たまを登録しました(ID 1)')).toBeVisible();
});

The test passed when I ran it. These are the values output by console.log:

text
$ npx playwright test

Running 1 test using 1 worker

url: http://localhost:3000/api/cats
method: POST
headers: {
  'sec-ch-ua-platform': '"Linux"',
  referer: 'http://localhost:3000/',
  'accept-language': 'en-US',
  'sec-ch-ua': '"Chromium";v="158", "Not.A/Brand";v="24", "HeadlessChrome";v="158"',
  'sec-ch-ua-mobile': '?0',
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/158.0.8127.36 Safari/537.36',
  'content-type': 'application/json',
  'x-client': 'web'
}
postData: {"name":"たま","age":3}
postDataJSON: { name: 'たま', age: 3 }
status: 201
response json: { id: 1, name: 'たま', age: 3 }
  ✓  1 [chromium] › tests/req.spec.ts:3:5 › 登録ボタンで、名前と年齢を POST で送る (233ms)

  1 passed (1.0s)

From the captured request (Request), I could get the following values:

  • url() and method(): the destination URL and the method, such as POST
  • postData(): the body as a string. It returns exactly what was sent, such as {"name":"たま","age":3}
  • postDataJSON(): the body parsed into an object. You can compare it directly with toEqual(). It also shows that the age was sent as the number 3, not as a string
  • headers(): an object of headers. All the names are lowercase, and the x-client header set on the page is included
  • response(): the response to this request. The status code was 201

About headers(), the Request API reference says that it does not return security-related headers, including Cookie-related ones, and that you should use await request.allHeaders() if you want to see all of them.

On the server side, I also logged the requests it received. The same body that the test extracted arrived at the server:

text
GET /api/cats?name=%E3%81%9F%E3%81%BE
POST /api/cats application/json {"name":"たま","age":3}

Starting to wait after the click causes a timeout

The waitForRequest() API reference says that it waits for a request matching the condition and returns it. To see what happens when it is called after the request has already been sent, I reversed the order: I wrote a test that presses the button, confirms that the success message appears on screen, and only then starts waiting.

ts
await page.getByRole('button', { name: '登録' }).click();
await expect(page.getByText('たまを登録しました(ID 1)')).toBeVisible();
// If you start waiting after confirming the screen changed, the request has already been sent
const request = await page.waitForRequest(
  (req) => req.url().endsWith('/api/cats') && req.method() === 'POST',
);

This test failed after waiting 30 seconds. The following output is the failing part, with the working directory path replaced by /path/to/app. The line numbers are those of the whole test file, not of the excerpt above.

text
  ✘  1 [chromium] › tests/req.spec.ts:3:5 › クリックのあとで待ち始める(失敗する書き方) (30.0s)


  1) [chromium] › tests/req.spec.ts:3:5 › クリックのあとで待ち始める(失敗する書き方) ───────────────────────────────────

    Test timeout of 30000ms exceeded.

    Error: page.waitForRequest: Test timeout of 30000ms exceeded.

       9 |   await expect(page.getByText('たまを登録しました(ID 1)')).toBeVisible();
      10 |   // If you start waiting after confirming the screen changed, the request has already been sent
    > 11 |   const request = await page.waitForRequest(
         |                              ^
      12 |     (req) => req.url().endsWith('/api/cats') && req.method() === 'POST',
      13 |   );
      14 |   expect(request.postDataJSON()).toEqual({ name: 'たま', age: 3 });
        at /path/to/app/tests/req.spec.ts:11:30

The server log shows POST /api/cats, so the request was sent. By the time waiting started, the POST had already gone out, so waitForRequest() kept waiting for a later POST until the test's time limit (30 seconds) was reached.

Diagram showing the difference in the order of calling waitForRequest. Above: waitForRequest is called before the click, so the POST is captured while waiting. Below: it is called after the click, so the POST has already been sent and the call keeps waiting for the next request, and the test times out after 30 seconds
waitForRequest() should be called before the click

If waitForRequest() times out during a test, check whether the line that starts waiting comes after the action that triggers the request.

Specifying only the URL captures the GET that was sent first

waitForRequest() also accepts a URL glob string or a regular expression instead of a function. However, when a GET and a POST are sent to the same URL, as on this page, a URL-only match may not select the POST. I waited with the regular expression /\/api\/cats/, and the result was as follows. The code is part of the test, and the lines that output url, method, and postDataJSON with console.log are omitted.

ts
const requestPromise = page.waitForRequest(/\/api\/cats/);
await page.getByRole('button', { name: '登録' }).click();
const request = await requestPromise;
text
url: http://localhost:3000/api/cats?name=%E3%81%9F%E3%81%BE
method: GET
postDataJSON: null
  ✘  1 [chromium] › tests/req.spec.ts:3:5 › URL だけで待つと、先に送られた GET をつかまえる (235ms)


  1) [chromium] › tests/req.spec.ts:3:5 › URL だけで待つと、先に送られた GET をつかまえる ─────────────────────────────

    Error: expect(received).toEqual(expected) // deep equality

    Expected: {"age": 3, "name": "たま"}
    Received: null

The regular expression also matches the duplicate-check GET that was sent first. In the test, waitForRequest() returned a GET with no body, and postDataJSON() was null. The error only shows Received: null, which makes it look as if the expected values were never sent. If this happens, print method() and url() of the captured request to find the cause.

On the other hand, when I waited with the glob string '**/api/cats', the captured request was the POST:

text
url: http://localhost:3000/api/cats
method: POST

According to the glob explanation in the network guide, a glob must match the entire URL. So it did not match the GET URL, which had ?name=… at the end. However, that happened only because the GET URL had a query string. If you need to distinguish requests by method, write the function form as in the first test, with req.method() === 'POST', to be sure.

For form submissions, postDataJSON() returns an object of keys and values

The same approach works when the request is sent by a submit button in a <form method="post"> rather than by fetch(). I placed a form on the page with an inquiry input field and a hidden field named topic (with the value cat).

ts
test('form の送信で送った中身を確かめる', async ({ page }) => {
  await page.goto('/');
  await page.getByLabel('お問い合わせ').fill('ごはんの量について');

  const requestPromise = page.waitForRequest('**/contact');
  await page.getByRole('button', { name: '送信' }).click();
  const request = await requestPromise;

  console.log('content-type:', request.headers()['content-type']);
  console.log('postData:', request.postData());
  console.log('postDataJSON:', request.postDataJSON());
  expect(request.postDataJSON()).toEqual({ message: 'ごはんの量について', topic: 'cat' });
  await expect(page.getByText('送信しました')).toBeVisible();
});
text
content-type: application/x-www-form-urlencoded
postData: message=%E3%81%94%E3%81%AF%E3%82%93%E3%81%AE%E9%87%8F%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6&topic=cat
postDataJSON: { message: 'ごはんの量について', topic: 'cat' }
  ✓  1 [chromium] › tests/req.spec.ts:3:5 › form の送信で送った中身を確かめる (246ms)

postData() returns the Japanese text still percent-encoded. postDataJSON() decoded it and returned an object of keys and values. The postDataJSON() description also says that for application/x-www-form-urlencoded it returns an object of keys and values, and otherwise parses the body as JSON. For form submissions too, you can compare with toEqual() without splitting the string yourself.

If you also want the response status code, use waitForResponse()

If you want to check the status code the server returned, in addition to the sent contents, you can wait for the response with page.waitForResponse(). You can reach the request from the response's request(). The waiting order is the same as with waitForRequest(): before the click. The following code is part of the test, and the lines that output status and postDataJSON with console.log are omitted.

ts
const responsePromise = page.waitForResponse(
  (res) => res.url().endsWith('/api/cats') && res.request().method() === 'POST',
);
await page.getByRole('button', { name: '登録' }).click();
const response = await responsePromise;

expect(response.status()).toBe(201);
expect(response.request().postDataJSON()).toEqual({ name: 'たま', age: 3 });
text
status: 201
postDataJSON: { name: 'たま', age: 3 }
  ✓  1 [chromium] › tests/req.spec.ts:3:5 › waitForResponse で、応答の状態コードと送った中身を確かめる (196ms)

Both approaches gave the same values (status code 201 and the sent body): waiting with waitForRequest() and getting the response with request.response(), or waiting with waitForResponse() and getting the request with response.request(). If you only need to check the sent contents, waitForRequest() is enough. If you also want to check the status code, waitForResponse() is simpler, since it waits for the response directly with a single await.

​Posted by 86