Search code examples
javascriptplaywright

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


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.


Solution

  • 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.