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.
You can also verify visibility using not. be. visible , and you can use and expect statement too.
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.
export function clickIfExist(element) {
cy.get('body').then((body) => {
if (body.find(element).length > 0) {
cy.get(element).click();
}
});
}
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')})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With