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

如何在Cypress中不使用eq()和XPath,通过data-testid选择CSS定位器的第n个元素

问题:如何在Cypress中通过data-testid选择第n个元素(禁用eq和XPath)

我正在使用Cypress进行测试,无法使用eq([index])方法,且XPath也不可用,请问如何通过data-testid属性选择CSS定位器的第n个元素?

示例DOM结构:存在多个带有data-testid="frame"的列表元素

<div data-component="layout" data-testid="frame" class="tzhgczFPvds">TEST</div>

需要将这类定位器用于以下拖拽测试代码的sourceitem和targetitem:

describe('Dragtest', () => {
  it('should dragndrop', () => {
    cy.visit('/yourpage')

    cy.get('.sourceitem').drag('.targetitem', options)
  })
})

解决方案

可以通过CSS原生伪类选择器实现,无需依赖Cypress的eq()或XPath,以下是几种常用写法:

  • :nth-child(n) 选择器:匹配父元素下的第n个子元素(计数从1开始),定位带data-testid="frame"的第n个元素写法:

    [data-testid="frame"]:nth-child(2)
    
  • :nth-of-type(n) 选择器:如果父元素包含不同类型的子元素,该选择器仅匹配同类型(这里是div)的第n个目标元素,写法:

    div[data-testid="frame"]:nth-of-type(3)
    
  • 快捷选择器:若仅需第一个或最后一个元素,可直接用:

    [data-testid="frame"]:first-of-type  /* 第一个元素 */
    [data-testid="frame"]:last-of-type   /* 最后一个元素 */
    

拖拽测试代码示例

将上述定位器替换到你的测试代码中,示例如下:

describe('Dragtest', () => {
  it('should dragndrop', () => {
    cy.visit('/yourpage')

    // 以第1个frame为源,第2个frame为目标进行拖拽
    cy.get('[data-testid="frame"]:nth-child(1)').drag('[data-testid="frame"]:nth-child(2)')
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:45:10