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

如何在Cypress中获取符合指定条件的表格行对应列元素

问题原因

你的代码问题出在Cypress命令的查找上下文逻辑:.get() 是全局DOM查询命令,不会限定在前一步.contains()匹配到的元素范围内搜索,所以无论前面匹配到哪个包含cypress-farm的元素,后续的.get(selector)都会返回页面上所有符合该选择器的元素,自然拿不到对应行的id。

修复方案

  1. 用.find()替代.get()做范围查询,.find()会限定在前一步返回的元素范围内搜索子元素
  2. 可显式补充行元素定位逻辑,避免匹配到行内零散元素导致上下文错误

修改后代码

public static addproductToFarm(selector:string, productName:string) {
    cy.get(".list")
        .contains("cypress-farm")
        .parents('tr') // 若.list本身就是行元素类名可省略此行
        .find(selector)
        .then(($temp)=>{
            const txt = $temp.text()
            cy.request({
                url: Cypress.env("api_server") + "products/",
                method: 'POST',
                form: false,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8',
                },
                body: {
                    availability: true,
                    category: {
                        hasOthers: false,
                        id: 1,
                        indexRanking: 0,
                        name: "Obst",
                        shown: true,
                        subCategories: [
                            null
                        ]
                    },
                    delivery: true,
                    description: productName,
                    descriptionExcerpt: "Cypress Product",
                    farmId: txt,
                    name: "Apple by Postman",
                    pickUp: true,
                    price: 10.00,
                    quantity: 10,
                    storageLimit: 10,
                    unit: "kg",
                    visibility: true
                }
            })
        })
    return this;
}

补充说明

如果你需要严格匹配整行包含目标值,也可以把查询逻辑改成cy.get('.list').filter(':contains("cypress-farm")').find(selector),效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 11:27:02