【问题标题】:Can Cypress give me an error message when there has been an error?出现错误时,赛普拉斯可以给我一条错误消息吗?
【发布时间】:2022-06-11 10:33:09
【问题描述】:

我的测试用例中有以下 sn-p:

cy.get('item_here').should('not.exist');

当“item_here”确实存在时,cypress 可以给我一条自定义错误消息吗?

谢谢,

【问题讨论】:

    标签: cypress


    【解决方案1】:

    您可以将日志消息链接到现有代码,并且仅当元素不存在时才会运行。

    cy.get('item_here').should('not.exist')
      .then(() => cy.log('no such element found'))  // Note; this is an additional log
    

    同时更改“成功”和“失败”消息很困难,因为赛普拉斯喜欢在任何失败或抛出错误时显示红色的 AssertionError 块。

    你可以使用should()回调版本,但是在里面使用expect(),否则你没有重试,

      cy.get('item_here').should($el => {
        expect($el, 'Cannot be found').to.not.exist    // expect causes retry for 4 seconds
                                                       
        Cypress.log({
          name: 'Missing',
          message: 'Cannot be found'
        })
      })
    
    
    

    【讨论】:

      【解决方案2】:

      您可以在.should() 的回调函数中抛出自己的错误。

      cy.get(".does-not-exist")
        .should("not.exist")
        .then(($el) => {
          if ($el == null) {
            throw new Error("Item does not exist in DOM");
          }
        });
      

      【讨论】:

      • 谢谢,您的陈述是否实质上是“如果这不等于 1 则错误?”
      • 如果 DOM 中没有一个元素与选择器匹配,它本质上会引发错误。如果您可以预期至少有一个匹配项,您可以将 !== 替换为 >=
      • 如果元素不存在,cy.get('item_here') 将失败,.should() 将永远不会运行。您需要在回调中使用.should('not.exist')expect 来修改cy.get('item_here') 的行为
      • 对。我错过了一步。已更新。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多