如何优化Cypress自定义命令以批量校验多元素禁用状态
修改后的Cypress自定义命令代码
直接替换原命令为以下代码,即可支持单个或多个testid的禁用状态校验:
Cypress.Commands.add("myElementState", (mySelector) => { // 统一处理参数:如果是单个字符串,转成单元素数组 const selectors = Array.isArray(mySelector) ? mySelector : [mySelector]; // 遍历所有选择器,逐个校验禁用状态 selectors.forEach(selector => { if (selector) { cy.getBySel(selector).should('be.disabled'); } }); });
关键修改点说明
- 参数兼容处理:通过
Array.isArray()判断传入的参数类型,不管是单个字符串(如"first-element")还是数组(如["first-element", "second-element"]),都统一转成数组处理,避免分支逻辑冗余 - 循环校验:用
forEach遍历所有testid,对每个元素执行禁用状态校验 - 修复语法错误:修正了原代码中函数定义括号缺失、
if语句未闭合、命令未正确收尾的语法问题
调用示例
// 校验单个元素 cy.myElementState("first-element"); // 校验多个元素 cy.myElementState(["first-element", "second-element", "third-element"]);
内容的提问来源于stack exchange,提问作者ZombiePie
相关产品推荐
相关产品推荐

