I need to catch an error when the should
assertion is failed.
Imagine that the first assertion for .should(‘not.exist’) is failed( the element is still visible)
Example of what I need(but this is not working for Cypress and JS):
this.containsInIframe('tr', assetName)
.find('div.loader', { timeout: 100000 })
.should('not.exist')
.catch((error) => {
this.reloadPage();
this.containsInIframe('tr', assetName)
.find('div.loader', { timeout: 100000 })
.should('not.exist');
});
How to deal with this situation using Cypress and JS? Can anyone suggest a way of solving this problem?
2
Answers
Catching the error is fairly complicated, as Cypress doesn’t operate exactly that way.
If you want to retry (as the catch code suggests), that feature is built in to Cypress runner.
Test retries
You could try recursion
It’s a bit hard to get the exact pattern from the code fragment, but the basic points are
recursion repeats the code until a condition is met (e.g
$loader.length === 0
which is equivalent to.should('not.exist')
but does not fail and stop the test)cy.reload()
clears the page and creates new elements, so don’t rely on any prior result, instead always re-query (looks like you are doing that)a small
cy.wait()
before the recursive call stops unnecessary cycles, but you should tune the wait time – enough so that reload and background action has completedthe recursive call should be done "on-the-queue" since you have Cypress queue commands involved, which is why it’s wrapped in
cy.then()
if you suspect there will be times when the loader never goes away, you should put a limit on the number of recursions – otherwise stack will overflow