typescriptcypresscypress-conditional-testing

Cypress - Conditional test with timeout


I'm trying to do something very similar to this post: https://stackoverflow.com/questions/56145926/how-to-check-if-element-exists-using-cypress-io

I'm using typsecript. Here's my code:

cy.get("body").then($body => {
            if ($body.find(this.timerLocator).length > 0) {
                return cy.get(this.timerLocator);
            }
            else {
                return cy.contains('No Match Found');
            }
});

The problem is that "this.timerLocator" can take up to 60s before appearing. The documentation for find commands mentions that we can pass an option 'timeout'. But when adding a timeout, I receive the following error message:

cy.get("body").then($body => {
            if ($body.find(this.timerLocator, {timeout: 60000}).length > 0) {
                return cy.get(this.timerLocator);
            }
            else {
                return cy.contains('No Match Found');
            }
        });

Expected 1 arguments, but got 2.ts(2554)

I also tried something much easier, like:

try {
    cy.get(this.timerLocator, { timeout: 60000 });            
} catch (error) {
    cy.contains('No Match Found');
}

But this is not working. I never reach the catch bracket.

Can anyone please help me on this one?

EDIT: I actually ended up using a multiple selector and it works great in my case. Here's my code:

const multiSelector = `${this.timerLocator}, :contains("No Match Found")`;
return cy.get(multiSelector, { timeout: 60000 });

Solution

  • You can't really do conditional $body.find(...) with a timeout.

    Since you have either/or and it looks like they are mutually exclusive, you can use multiple selector

    // this selector looks for either timerLocator or element with "No Match Found"
    const multiSelector = `${this.timerLocator}, :contains("No Match Found")`;
    
    cy.get(multiSelector, {timeout:60000})
      .then($timerOrNoMatch =>
        ...
      })