Playwright Wait for Response

Profile picture for user arilio666

The playwright can wait for network responses triggered by clicking or other actions in a browser.

 await page.waitForResponse('response url');

Let us see it in action. For this, we will be working on the reqres API site.

await page.goto('https://reqres.in/')
await page.locator('//li[@data-id="users-single"]').click()
await Promise.all([
       page.waitForResponse(resp => resp.url().includes('/api/users/2') && resp.status() === 200),
       page.locator("(//span[@class='url'])[1]").click()
       
   ]);
 await expect(page.locator('body > pre:nth-child(1)')).toHaveText('{"data":{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://reqres.in/img/faces/2-image.jpg"},"support":{"url":"https://reqres.in/#support-heading","text":"To keep ReqRes free, contributions towards server costs are appreciated!"}}')
  • Initially, we click on the single-user GET method.
  • Within a promise, we were wrapping the clicking of the URL, the response wait time, and providing the GET request URL.
  • This will prevent race conditions after clicking on the link and waiting for the URL response.
  • In the end, we have asserted with expect for the JSON body it presents itself after clicking.
await page.goto('https://reqres.in/')
await page.locator('//li[@data-id="users-single"]').click()
const [response] = await Promise.all([
       page.waitForResponse(resp => resp.url().includes('/api/users/2') && resp.status() === 200),
       page.locator("(//span[@class='url'])[1]").click()
       
   ]);
   console.log(response.body())
 await expect(page.locator('body > pre:nth-child(1)')).toHaveText('{"data":{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://reqres.in/img/faces/2-image.jpg"},"support":{"url":"https://reqres.in/#support-heading","text":"To keep ReqRes free, contributions towards server costs are appreciated!"}}')
  • We can also get the response body by storing the Promise into a variable and returning it.