How to check if specific action made a request using playwright?

Viewed 949

It's my first time using Playwright and I just can't figure out how to check if a request is made to the server. I want to press a button that sends request and and validate if it was successful or not. I am using chromium from Playwright and making tests with Mocha and Chai. This is my code:

const browser = await chromium.launch();    
const page = await browser.newPage();

await page.goto(url);
await page.click('text=Send');
// Validate if the request is send

await browser.close();

I may be trying to do it wrong, but I don't have much experience with Playwright, so any help will be appreciated.

2 Answers

You can use page.waitForRequest, using the urlOrPredicate parameter to verify that the request matches your expectation.

I'm not sure I have it clear. As I see it, you'd need to make the requests to the API. You can check it in the docs. For example, after clicking the button:

test('api', async({ request }) => {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.goto(url);
    await page.click('text=Send');
    // your api call(s)
    const req = await request.YOUR_REQ_METHOD('https://THE_URL_NEEDED');
    // your assertion(s)
    expect(req.ok()).toBeTruthy();
});

I'd just add, and I'm not saying this is the case, always consider if you need the use of a browser for achieving your goal.

Related