Din*_*esh 5 uncaught-exception cypress
我有以下示例脚本来试验 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})
})
})
Run Code Online (Sandbox Code Playgroud)
请注意,我的网页中没有 id notfound 的元素。
小智 5
未捕获的异常仅适用于应用程序错误。赛普拉斯捕获测试代码中的故障,但随后将其报告为测试失败。
为了防止这种情况,您可以使用失败事件
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')
})
Run Code Online (Sandbox Code Playgroud)
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)
})
Run Code Online (Sandbox Code Playgroud)
测试 - 捕获错误并选择性地忽略它是否有特定消息
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)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8543 次 |
| 最近记录: |