Cypress中如何将should表达式转换为软断言
Cypress 软断言适配DOM disabled属性检查方案
软断言不会因为单个校验失败中断测试流程,核心是捕获断言错误暂存,待所有测试步骤执行完成后统一汇总抛出,针对disabled这类DOM状态/属性检查,不需要做特殊的逻辑适配,直接用以下两种方案实现即可:
无额外依赖自实现方案
直接在项目的cypress/support/commands.js文件中添加以下封装,完全复用Cypress原生断言能力,兼容所有should支持的检查场景:
// 软断言错误缓存 let softAssertErrors = [] // 封装通用软断言命令,继承所有原生should的断言规则 Cypress.Commands.add('softShould', { prevSubject: 'element' }, (subject, assertChain, expectValue) => { try { expectValue ? cy.wrap(subject).should(assertChain, expectValue) : cy.wrap(subject).should(assertChain) } catch (e) { softAssertErrors.push(`元素${subject.selector}校验失败:预期${assertChain}${expectValue ? ' ' + expectValue : ''}`) } return cy.wrap(subject) }) // 统一校验所有软断言结果 Cypress.Commands.add('verifyAllSoft', () => { const errList = [...softAssertErrors] softAssertErrors = [] if (errList.length) throw new Error(`累计${errList.length}个软断言失败:\n${errList.join('\n')}`) }) // 每个用例执行前清空错误缓存 beforeEach(() => softAssertErrors = [])
封装完成后,把原有测试代码中的should替换为softShould即可,be.disabled、have.attr这类检查规则不需要做任何修改:
// 测试用例代码 cy.get('[data-id="name"]').softShould('not.be.disabled') // 该断言失败后不会终止流程,会继续执行后续检查 cy.get('[data-id="email"]').softShould('be.disabled') cy.get('[data-id="password"]').softShould('have.attr', 'disabled') // 所有表单测试点遍历完成后,统一抛出所有收集到的错误 cy.verifyAllSoft()
成熟插件方案
如果不想自行维护封装逻辑,可以使用Cypress生态的软断言插件,完成安装配置后,只需要在原有断言链中加入soft标记即可,原生支持所有DOM属性、状态检查:
cy.get('[data-id="name"]').should('soft.not.be.disabled') cy.get('[data-id="email"]').should('soft.be.disabled') // 失败不中断 cy.get('[data-id="password"]').should('soft.have.attr', 'disabled')
插件默认会在单个用例执行完成后自动汇总所有软断言失败信息,不需要手动调用统一校验方法。
内容的提问来源于stack exchange,提问作者user19475236
相关产品推荐
相关产品推荐

