Cypress cy.get() 内置了重试功能,因此如果一个元素正在加载或动画,该命令最终会抓取该元素。
但是 jQuery 等效的 Cypress.$(.${selector}) 没有重试。您可以尝试在您的函数中构建一些轮询,但工作量很大,为什么赛普拉斯没有内置 cy.maybe(selector)?
如果您知道存在哪些元素,Cypress 测试效果最好,有很多关于它的文档,但总会有边缘情况。
我见过的唯一方法是在这里How can manage the application flow, if the element xpath is not present,使用cypress-xpath 插件和count() 函数。
cy.xpath(`count(//${element}[@class="${selector}"])`) // ok with async content
.then(count => {
const selector = count ? selector : defaultSelector;
您可能正在寻找jQuery OR Selector,它允许您在逗号后提供默认选择器。
如果DOM是这样的
<div class="pick-me">one</div>
<div class="or-me">two</div>
此测试将获取 div.pick-me
cy.get('.pick-me, .or-me') // jQuery OR selector
.eq(0) // in case both match, take first
.should('have.class', 'pick-me'); // first selector is used
但如果 DOM 没有第一类,
<div class="dont-pick-me">one</div>
<div class="or-me">two</div>
该命令将返回默认选择器
cy.get('.pick-me, .or-me') // jQuery OR selector
.eq(0) // in case both match, take first
.should('have.class', 'or-me'); // default selector is used