gpt4 book ai didi

未捕获异常的 Cypress 不起作用

转载 作者:行者123 更新时间:2023-12-04 01:02:00 25 4
gpt4 key购买 nike

我有以下示例脚本来试验 Cypress 中的异常处理。但是异常没有被捕获。我在这里缺少什么?

Cypress.on('uncaught:exception', (err, runnable) => {
Cypress.log("this is top-level exception hadling")
return false
})

context('Actions', () => {

it('sample_testing', () => {

cy.on('uncaught:exception', (err, runnable) => {
cy.log("this is test-level exception hadling")
return false
})

cy.get("#notfound", {timeout:1000})
})

})
请注意,我的网页中没有未找到 id 的元素。

最佳答案

未捕获的异常仅针对应用程序错误。测试代码中的失败会被 Cypress 捕获,但随后会报告为测试失败。
测试失败
为了防止这种情况,您可以使用 fail event

Cypress.on('fail', (error, runnable) => {
debugger

// we now have access to the err instance
// and the mocha runnable this failed on

throw error // throw error to have test still fail
})

it('calls the "fail" callback when this test fails', () => {
// when this cy.get() fails the callback
// is invoked with the error
cy.get('element-that-does-not-exist')
})
未捕获的异常
看看食谱 Handling Application Errors
app.js - 抛出错误
document.getElementById('error').addEventListener('click', () => {
console.log('application will throw an error in 1 second')
setTimeout(() => {
console.log('application is about to throw an error')
throw new Error('Things went bad')
}, 1000)
})
测试 - 捕获错误并有选择地忽略它是否有特定消息
  it('can be ignored', () => {
/**
* By using "cy.on()" we can ignore an exception in the current test only.
* If you want to register exception handler for all tests using "Cypress.on()"
* @see https://on.cypress.io/catalog-of-events
* @param {Error} e The exception we caught
* @param {Mocha.Runnable} runnable is the current test or hook during which the error is caught
*/
cy.on('uncaught:exception', (e, runnable) => {
console.log('error', e)
console.log('runnable', runnable)

// we can simply return false to avoid failing the test on uncaught error
// return false
// but a better strategy is to make sure the error is expected
if (e.message.includes('Things went bad')) {
// we expected this error, so let's ignore it
// and let the test continue
return false
}
// on any other error message the test fails
})

cy.visit('index.html')
cy.get('button#error').click()
// the error happens after 1000ms
// we can use hard-coded wait, see the other test
// to learn how to avoid an unnecessary wait
cy.wait(1500)
})

关于未捕获异常的 Cypress 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68001586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com