How to check for an element that may not exist using Cypress

Charles Anderson picture Charles Anderson · Dec 12, 2017 · Viewed 27.9k times · Source

I am writing a Cypress test to log into a website. There are username and password fields and a Submit button. Mostly logins are straightforward, but sometimes a warning dialog appears first that has to be dismissed.

I tried this:

    cy.get('#login-username').type('username');
    cy.get('#login-password').type(`password{enter}`);

    // Check for a possible warning dialog and dismiss it
    if (cy.get('.warning')) {
        cy.get('#warn-dialog-submit').click();
    }

which works fine, except that the test fails if the warning doesn't appear:

CypressError: Timed out retrying: Expected to find element: '.warning', but never found it.

Then I tried this, which fails because the warning doesn't appear fast enough, so Cypress.$ doesn't find anything:

    cy.get('#login-username').type('username');
    cy.get('#login-password').type(`password{enter}`);

    // Check for a possible warning dialog and dismiss it
    if (Cypress.$('.warning').length > 0) {
        cy.get('#warn-dialog-submit').click();
    }

What is the correct way to check for the existence of an element? I need something like cy.get that doesn't complain if the element can't be found.

Answer

Ran Adler picture Ran Adler · Jan 6, 2020
export function clickIfExist(element) {
    cy.get('body').then((body) => {
        if (body.find(element).length > 0) {
            cy.get(element).click();
        }
    });
}