Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am writing a Cypress test to log in to 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.

like image 740
Charles Anderson Avatar asked Dec 12 '17 13:12

Charles Anderson


People also ask

How do you check if an element does not exist in Cypress?

You can also verify visibility using not. be. visible , and you can use and expect statement too.

How do you select the invisible element in Cypress?

Cypress has another technique for handling hidden elements. For example, to click a hidden element we can use the Cypress command click and pass the option {force : true} as a parameter to it - click({ force: true }). This modifies the hidden characteristics of the hidden element and we can click it.


2 Answers

export function clickIfExist(element) {
    cy.get('body').then((body) => {
        if (body.find(element).length > 0) {
            cy.get(element).click();
        }
    });
}
like image 92
Ran Adler Avatar answered Oct 18 '22 03:10

Ran Adler


export const getEl = name => cy.get(`[data-cy="${name}"]`)

export const checkIfElementPresent = (visibleEl, text) => {
   cy.document().then((doc) => {
     if(doc.querySelectorAll(`[data-cy=${visibleEl}]`).length){
      getEl(visibleEl).should('have.text', text)

      return ;
   }
getEl(visibleEl).should('not.exist')})}
like image 3
nikolay kozub Avatar answered Oct 18 '22 03:10

nikolay kozub