How to wait for request response but ignore if it exceed a certain time

574 Views Asked by At

In my test I want to wait for a request but if a particular timeout expires, I want to ignore the request response. But using the waitForResponse function, if the request never responds before the timeout the page is closed and the test ends.

So, how to optionally look for the response to test degraded mode in Playwright ?

2

There are 2 best solutions below

0
On

You can catch the timeout error:

const response = await page.waitForResponse(...).catch(() => false);

if (response) {
  // no throw, assert on the response
}
else {
  // it threw, no response arrived
}

That said, it's an antipattern to have conditions in tests. Tests should be deterministic to the extent you can make them. If you have two different application states to test, prefer writing separate tests, taking care to set up the necessary conditions to reproduce each application state.

Cypress has a thorough article on conditional testing, and the main points hold true in Playwright as well.

2
On

You can use Promise.race along with page.waitForResponse to set a timeout for waiting for the response. If the response is received within the specified time, you can test it. If not, you can continue with your test.