You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化重复冗余的Cypress代码,避免复制粘贴相同逻辑?

Cypress重复操作代码精简方案

这里直接给3种不同场景的精简写法,按需选择即可:

方案1:下标循环(适合确定要操作前N个元素的场景)

把重复的选择器、配置项抽成常量,遍历下标执行相同操作:

// 抽离公共变量消除重复
const targetInput = 'input[ng-change="$matterHourCtrl.forceRound()"]'
const typeConfig = { multiple: true, force: true }

// 遍历0-3下标批量执行
;[0,1,2,3].forEach(idx => {
  cy.get(targetInput).eq(idx).dblclick().type('{uparrow}', typeConfig)
})

方案2:自动遍历匹配元素(适合要操作所有符合选择器的元素的场景)

不用写死下标,Cypress原生each()方法会自动遍历所有匹配到的元素,后续元素数量变化也不用改代码:

cy.get('input[ng-change="$matterHourCtrl.forceRound()"]').each($input => {
  cy.wrap($input).dblclick().type('{uparrow}', { multiple: true, force: true })
})

方案3:封装全局自定义命令(适合多测试用例都需要用到该操作的场景)

先在全局命令文件中封装公共操作:

// cypress/support/commands.js 中添加定义
Cypress.Commands.add('adjustMatterHourInput', (index) => {
  const selector = 'input[ng-change="$matterHourCtrl.forceRound()"]'
  cy.get(selector).eq(index).dblclick().type('{uparrow}', { multiple: true, force: true })
})

测试用例中直接调用即可:

// 单个调用
cy.adjustMatterHourInput(0)
// 批量调用
;[0,1,2,3].forEach(cy.adjustMatterHourInput)

内容的提问来源于stack exchange,提问作者TanzaKnight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:15:05