if-else 包含 cy.get 作为条件

问题描述 投票:0回答:1

我正在尝试创建一个 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
1个回答
0
投票

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 {
      ...   
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.