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

Cypress:替换contains()为自动返回首个元素的命令(无需first/last)

解决Cypress中contains()返回多个元素的问题

自定义自动取首个匹配的命令

直接在cypress/support/commands.js里添加自定义命令,封装contains()+first()的逻辑,以后用这个命令就不用手动加first()了:

// 支持两种调用方式:带选择器或不带
Cypress.Commands.add('containsFirst', (selector, content, options = {}) => {
  return cy.contains(selector, content, options).first();
});

Cypress.Commands.add('containsFirst', (content, options = {}) => {
  return cy.contains(content, options).first();
});

替换你的原代码时,注意把.get('[data-test="removebtn"]')改成.find()——用get会全局重新查询元素,而find才是在前面匹配到的元素内部找子按钮:

cy.get('[data-cy="todo"]').children('[data-test="ttt"]')
  .containsFirst(id)
  .find('[data-test="removebtn"]')
  .click();

额外说明

你原代码里用get导致的问题可能比contains返回多个元素更严重——get会脱离之前的元素链,直接从整个页面找[data-test="removebtn"],哪怕你加了first()也可能点错按钮。换成find才能保证是在目标todo项里找删除按钮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:06:09