【问题标题】:Error handling using the catch block in cypress使用 cypress 中的 catch 块进行错误处理
【发布时间】:2019-06-24 20:44:39
【问题描述】:

我正在尝试处理 Cypress 中的错误,但 Cypress 应用程序抛出错误

cy.get('button[name="continue"]',{timeout: 30000})
  .catch((err) => {
    cy.console.log("error caught");
  })

我得到的错误:

TypeError: cy.get(...).catch 不是函数

【问题讨论】:

    标签: cypress


    【解决方案1】:

    tl;博士

    赛普拉斯没有.catch 命令,错误消息清楚地说明了这一点。

    赛普拉斯中的异常处理

    documentation on error recovery 明确指出:

    以下代码无效,您无法向赛普拉斯命令添加错误处理。该代码仅用于演示目的。

    cy.get('button').contains('hello')
      .catch((err) => {
        // oh no the button wasn't found
        // (or something else failed)
        cy.get('somethingElse').click()
      })
    

    他们故意忽略了这一点,并在文档中详细解释了为什么你不应该这样做。

    如果你真的想要,你可以捕获未捕获的异常,只需尝试Catalog of Events on this matter的建议:

    it('is doing something very important', function (done) {
      // this event will automatically be unbound when this
      // test ends because it's attached to 'cy'
      cy.on('uncaught:exception', (err, runnable) => {
        expect(err.message).to.include('something about the error')
    
        // using mocha's async done callback to finish
        // this test so we prove that an uncaught exception
        // was thrown
        done()
    
        // return false to prevent the error from
        // failing this test
        return false
      })
    
      // assume this causes an error
      cy.get('button').click()
    })
    

    【讨论】:

    • 不幸的是,当你调用 'done' 函数时,它会给你这个错误 -docs.cypress.io/guides/references/…
    • 任何解决此问题的方法!我真的需要这个。 (我需要它的原因是:信用卡在一段时间后被阻止,所以我想检测它何时被阻止并尝试另一对)
    【解决方案2】:

    赛普拉斯网站的官方解释如下:

    如果测试编写者不能准确预测系统的给定状态,那么赛普拉斯也不能。错误处理没有提供额外的证据,这可以确定地完成。

    您应该将 Cypress 中的失败命令视为类似于服务器端代码中未捕获的异常。在这些情况下无法尝试恢复,因为系统已转换为不可靠状态。相反,您通常总是选择崩溃和记录。当赛普拉斯未能通过测试时——这正是它正在做的事情。退出,跳过测试中的任何剩余命令,并注销失败。

    如果您无法准确了解应用程序的状态,那么无论您有什么可用的编程习惯 - 您都无法编写 100% 确定性测试。

    你可以尝试条件测试,但要确保你的 DOM 是稳定的。

    对 DOM 进行条件测试的唯一方法是,如果您 100% 确定状态已“稳定”并且无法更改它。 这就对了!在任何其他情况下,如果您尝试依赖 DOM 的状态进行条件测试,您将遇到不稳定的测试。

    来源:https://docs.cypress.io/guides/core-concepts/conditional-testing#Error-Recovery

    【讨论】:

      猜你喜欢
      • 2012-04-20
      • 2013-01-21
      • 1970-01-01
      • 2023-01-10
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 2022-06-16
      相关资源
      最近更新 更多