13

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

Vladimir Krygin
  • 439
  • 2
  • 6
  • 18

3 Answers3

29

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.

pavelsaman
  • 7,399
  • 1
  • 14
  • 32
8

Alternatively, you can assign a promise, then later wait for it:

const responsePromise = page.waitForResponse(resp => resp.url().includes('/api/contacts') && resp.status() === 400);
await contacts.clickSaveBtn();
const response = await responsePromise;

It's more readable and you get the response value.

1

I was looking for the same, this worked for me:

 const response = await page.waitForResponse((response) => response.url().includes("/api/contacts"));
    
     // Assert the response status and body
     const responseBody = await response.json();
     expect(response.status()).toBe(200);
Kimy BF
  • 1,029
  • 3
  • 13
  • 23