我正在尝试创建一个 if-else 条件,其中包括
cy.get()
if (!cy.get('.modal.modal--active')) {
cy.reload()
} else {
// some codes here
}
测试代码后,
.modal.modal--active
元素不存在,而不是执行cy.reload()
行,而是返回错误。
期望找到元素:
.modal.modal--active
,但从未找到。
是否可以让 if 块运行而不返回 AssertionError?
Cypress 命令应该链接起来,而不是用作
if()
语句中的表达式。
当未找到 cy.get(something)
时,
something
测试失败。
添加像
cy.get(something).should('not.exist')
这样的否定断言会起到相反的作用,当未找到 something
时,它会通过。
第三种方法(未记录)是
.should(() => undefined)
,类似这样
cy.get('.modal.modal--active')
.should(() => undefined)
.then(activeModal => {
const found = activeModal.length
if (!found) {
cy.reload()
} else {
...
}
})
记录的方法是使用 jQuery
.find()
,如下所示:
cy.get('body').then((body) => { // always succeeds
const modalActive = body.find('.modal.modal--active')
const found = activeModal.length
if (!found) {
cy.reload()
} else {
...
}
})