首页 > 解决方案 > 如何以与 selenium 中类似的方式处理 Cypress 中的异常

问题描述

在 selenium 中,我们可以处理异常。如果任何测试用例中发生任何异常,它将跳转到我们可以在 selenium 中执行的下一个测试用例。但我很困惑,我们怎么能在赛普拉斯做到这一点。以下面的例子

 it('Test Case 1', function () {
        cy.visit('https://habitica.com/login')
        cy.get('form').find('input[id="usernameInput"]').click().type("username")
        cy.get('form').find('input[id="passwordInput"]').click().type("password")
        **cy.get('.btn-info').click()** 
        cy.get('.modal-dialog').find('button[class="btn btn-warning"]').click()
        cy.get('.start-day').find('button').click({force:true})
    })

 it('Test Case 2', function () {
        cy.visit('https://habitica.com/login')
        cy.get('form').find('input[id="usernameInput"]').click().type("username")
        cy.get('form').find('input[id="passwordInput"]').click().type("password")
        cy.get('.btn-info').click() 
        cy.get('.modal-dialog').find('button[class="btn btn-warning"]').click()
        cy.get('.start-day').find('button').click({force:true})
    })

假设浏览器在测试用例 1 中找不到点击元素(用粗体突出显示),那么它将跳转到测试用例 2。

我们如何在 Cypress 中做到这一点?

请帮助我

像 Unable to Fine element 或其他类似的例外。

除了这个例子,我们如何处理异常或错误。

标签: cypress

解决方案


尽管赛普拉斯团队说我们需要尽可能避免条件测试(也许需要改变你的方法)。但是,在您的情况下,您可以包含条件测试:

cy.get('.btn-info').then((body) => {
 if (body.length > 0) { // continues if the element exists
    cy.get('.btn-info').click();
    cy.get('.modal-dialog').find('button[class="btn btn-warning"]').click()
    cy.get('.start-day').find('button').click({force:true})
 } // if the above condition is not met, then it skips this the commands and moves to the next test
});

推荐阅读