skip to Main Content

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


  1. 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

    it('retries the test', {retries: {runMode: 2, openMode: 1}}, function() {
      .. test code 
    })
    
    Login or Signup to reply.
  2. You could try recursion

    function reloadUntilLoaderHasGone() {
      this.containsInIframe('tr', assetName)
        .then($tr => {
          const $loader = $tr.find('div.loader')
          if ($loader.length > 0) {
            cy.reload()
            cy.wait(300)
            cy.then(() => reloadUntilLoaderHasGone())
          }
        })
    }
    reloadUntilLoaderHasGone()
    

    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 completed

    • the 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search