使用 cypress 中的 catch 块进行错误处理

kis*_*mar 4 cypress

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

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

我得到的错误:

类型错误:cy.get(...).catch 不是函数

tot*_*dli 6

tl;博士

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

Cypress 中的异常处理

关于错误恢复文档明确指出:

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

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

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

如果你真的想要,你可以捕获未捕获的异常,只需尝试事件目录关于此事的建议

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()
})
Run Code Online (Sandbox Code Playgroud)