How do I check network response in playwright?

Viewed 24

I want to test the network https status response with playwright.

test.only('Rights.2: Users without the required author role do not have access.', async ({page}) => {
    await login(page, 'xxx', "password.xxx");
    const search = await searchForProcess(page, `${process.process1.title}`);
    await login(page, 'PortalUser');
    const open = await openProcess(page, `${process.process1.title}`);
});

So I tried with this

expect(response.status()).toEqual(403);

But it won't work, because response is not defined. Thats curious, because Playwright does document the "response.status()" as a function.

Can somebody help?

1 Answers

You could try page.waitForResponse(). Official docs: https://playwright.dev/docs/api/class-page#page-wait-for-response

Here is an example where we click a button and we want to monitor that certain API calls actually happen and that they have certain response statuses:

// Start waiting for all required API calls as we select company.
// We can accept only 200 but we could accept 403 like with /api/Environment/

await Promise.all([
            page.waitForResponse(resp => resp.url().includes('/api/Environment/') && (resp.status() === 200 || resp.status() === 403)),
            page.waitForResponse(resp => resp.url().includes('/api/Security/') && (resp.status() === 200)),
            // We already started waiting before we perform the click that triggers the API calls. So now we just perform the click
            page.locator('div[role="gridcell"]:has-text("text")').click()
]);

If you wish to validate other reponse data, see: https://playwright.dev/docs/api/class-response

If you want to monitor all network traffic, this official docs would be more suitable: https://playwright.dev/docs/network#network-events

Related