如何使用 cypress 在 if 条件下传递断言,而不在断言失败时停止执行

0 javascript automation cypress cypress-conditional-testing

我试图将断言传递给 if 条件,并在满足条件时执行一个逻辑,在条件失败时执行另一个逻辑。

由于测试因断言失败而失败,我无法达到预期的结果。

我尝试了以下...

if(cy.get("div").length \> 0) {
  cy.log("print this")
} else {
  cy.log("print this")
}
Run Code Online (Sandbox Code Playgroud)

或者

if(cy.get("div").should('have.length.greaterThan', 0) {
  cy.log("print this")
} else {
  cy.log("print this")
}
Run Code Online (Sandbox Code Playgroud)

Tes*_*ick 8

如果您想检查命令的结果而不使测试失败,请添加.should()返回 的undefined

cy.get('div#does-not-exist')
  .should(() => undefined)          // stops the above failing
  .then($result => {
    if ($result.length) {
      cy.log('Found')
    } else {
      cy.log('Not found')    
    }
  })
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这是有效的,因为.should() 修改cy.get().

例如,如果你运行cy.get('div#does-not-exist').should('not.exist')它就会通过。shouldnot中的 反转(否定) 中的隐式断言cy.get()

它还会更改隐式断言,但允许您在链的下游.should(() => undefined)执行检查。if()

请注意,到目前为止提到的所有方法都不允许检查加载过程中的元素,即没有内置重试功能。

为此,您需要轮询元素,如下所示
如何使用 Cypress 检查可能不存在的元素


小智 6

将传递的断言if()更改cy.get()Cypress.$().

if(Cypress.$('div').length > 0) {
  cy.log("print this")
} else {
  cy.log("print that")
}
Run Code Online (Sandbox Code Playgroud)

cy.get()是一个Cypress.$()重试直到超时然后失败的包装器。

Cypress.$()如果失败,则只返回一个 jQuery 对象length === 0,但无论哪种情况测试都会继续。

在运行任何 条件之前,请确保页面已完成加载(尚未响应任何提取)if()