Search code examples
javascriptprotractorcypressexpected-condition

Is there any way in cypress to wait for multiple expected conditions


So I am trying to migrate our existing protractor test suite to cypress. For one of the tests, we have scenario where we can have two expected conditions which easier to handle in protractor. But I was wondering if there is any similar cypress command function to achieve that?? sharing the code snippet

confirmation.getConfirmButton().click().then(() => {

            // We will either get a successful cancellation OR an alert modal with an OK
            // button saying that the contract cannot be cancelled yet

            browser.wait(ExpectedConditions.or(
                ExpectedConditions.textToBePresentInElement(this.getViewAllFirstStatus(), "Cancelled"),
                ExpectedConditions.elementToBeClickable(this.getModalOkButton())
            ), 5000);

            this.getModalOkButton().isPresent().then((present) => {
                if (present) {
                    this.getModalOkButton().click().then(() => {
                        browser.sleep(8000).then(() => {
                            this.cancelFirstContract();
                        });
                    });
                }
            });
        });


Solution

  • I think what you want to do in Cypress is use the jQuery multiple selector.

    This will essentially wait for one selector or the other, equivalent to the Protractor expression ExpectedConditions.or(...).

    Whichever selector appears first will pass on as "subject" on the command chain.

    If neither element turns up within 10 seconds, the test fails.

    const cancelledStatus = 'span:contains("Cancelled")';  // adjust as appropriate
    const modalOkButton = 'button:contains("Ok")';         // adjust as appropriate 
    
    const multipleSelector = `${cancelledStatus}, ${modalOkButton}`
    
    cy.get(multipleSelector, {timeout:10000})
      .then($subject => {
        if ($subject.text() === "Ok") {  // equiv to "getModalOkButton().isPresent()"
          cy.wrap($subject).click()
        }
      })