乐闻世界logo
搜索文章和话题

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

2个答案

1
2

hasClass() is a method for CSS selectors or has() is an internal method in jQuery, used to check if an element with the specified class name exists. You can then return a boolean value for assertion purposes.

javascript
Cypress.Commands.add('isExistElement', selector => { cy.get('body').then(($el) => { if ($el.has(selector)) { return true } else { return false } }) });

Then, you can create a special Cypress method using a TypeScript file (index.d.ts) and make it chainable.

typescript
declare namespace Cypress { interface Chainable { isExistElement(cssSelector: string): Cypress.Chainable<boolean> } }

As illustrated below:

javascript
shouldSeeCreateTicketTab() { cy.isExistElement(homePageSelector.createTicketTab).should("be.true"); }
2024年6月29日 12:07 回复

Use element polling to check for elements and avoid test failures.

Within the maximum wait time, either the dialog never appears, or this code closes it.

javascript
cy.get('#login-username').type('username'); cy.get('#login-password').type(`password{enter}`); const ifElementExists = (selector, attempt = 0) => { if (attempt === 100) return null // if not found, return null if (Cypress.$(selector).length === 0) { cy.wait(100, {log:false}) // wait in small increments getDialog(selector, ++attempt) // try again } return cy.get(selector, {log:false}) // done, return the element } ifElementExists('.warning').then($el => { if ($el?.length) { $el.find('#warn-dialog-submit').click() } })
2024年6月29日 12:07 回复

你的答案