Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for requests and validate responses using playwright?

This is my first time using playwright and I can't figure out how to wait for requests and validate responses. I've been using cypress for a quite a long time, and it was pretty easy to manage network requests. For example, I need to validate response after clicking a button and this is how I would do it with cypress:

        cy.server()
        cy.route('POST', '/api/contacts').as('newContact')

        cy.get('.btn').click()

        cy.wait('@newContact').then((response) => {
            expect(response.status).to.eq(400)
            expect(response.responseBody.data.name).to.eq('abcde')
        })

And this is how I'm trying to do the same thing with playwright, but it validates GET request that was sent long before it even clicked save button. I can't figure out how to manage this request properly and that's a show stopper for my test suite:

        await contacts.clickSaveBtn()

        await page.waitForResponse((resp) => {
            resp.url().includes('/api/contacts')
            expect(resp.status()).toBe(400)
        })

Any help or advice would be really appreciated

like image 987
Vladimir Krygin Avatar asked Sep 03 '25 05:09

Vladimir Krygin


1 Answers

What you need to do is first start waiting for the response and then click, so the waitForResponse() can catch the actual response coming as a result of the click.

await Promise.all([
    page.waitForResponse(resp => resp.url().includes('/api/contacts') && resp.status() === 400),
    contacts.clickSaveBtn()
]);

This should handle the possible race condition.

like image 107
pavelsaman Avatar answered Sep 04 '25 18:09

pavelsaman