Monday, May 20, 2024
199
rated 0 times [  200] [ 1]  / answers: 1 / hits: 23603  / 3 Years ago, wed, march 24, 2021, 12:00:00

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


More From » automated-tests

 Answers
2

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.


[#50337] Saturday, March 6, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;