Cypress处理Web Table时数组元素拆分及空格一致性问题求助
解决Cypress表格数据拆分与格式统一问题
你要解决的核心问题是把表格里连在一起的字段按规则拆开,修正空格混乱的问题,最终得到格式统一的数组。下面是具体的解决办法:
问题拆解
实际输出里有几个明显的问题:
- 第一个单元格的
1234random9-Dec-2022没拆成id、file_name、date三个独立字段 privateNot要拆成private,还要和后面的Scheduled合并成NotScheduled- 数组里有空字符串,得过滤掉
修改后的代码
describe('Webtable test', () => { it('Whole table data', function() { cy.get('#query-table tbody tr') .should('have.length', 10); cy.get('#query-table tbody tr:eq(1) td').should('have.length', 7); cy.get('#query-table tbody tr').each(($row) => { // 存储当前行处理后的所有字段 const rowFields = []; cy.wrap($row).find('td').each(($td, index) => { const tdText = $td.text().trim(); switch(index) { case 0: // 拆分第一个单元格:数字id + 字母文件名 + 日期 const id = tdText.match(/^\d+/)[0]; // 提取开头的数字ID const date = tdText.match(/\d{1,2}-[A-Za-z]{3}-\d{4}/)[0]; // 提取日期格式内容 const fileName = tdText.replace(id, '').replace(date, '').trim(); // 剩余部分作为文件名 rowFields.push(id, fileName, date); break; case 1: // 时间字段直接加入数组 rowFields.push(tdText); break; case 2: // 用户名直接加入数组 rowFields.push(tdText); break; case 3: // 拆分privateNot为private,临时存储Not用于后续合并 if (tdText === 'privateNot') { rowFields.push('private'); this.notPrefix = 'Not'; } break; case 4: // 合并Not与Scheduled为NotScheduled if (this.notPrefix && tdText === 'Scheduled') { rowFields.push(`${this.notPrefix}${tdText}`); delete this.notPrefix; // 清空临时变量 } else { rowFields.push(tdText); } break; default: // 过滤空字符串,不加入数组 if (tdText) rowFields.push(tdText); break; } }).then(() => { // 打印处理后的行数据 cy.log('处理后的行数据:', rowFields); // 可添加断言验证结果是否符合预期 expect(rowFields).to.deep.equal([ "1234", "random", "9-Dec-2022", "15:16:51", "User66", "private", "NotScheduled" ]); }); }); }); });
重点逻辑解释
- 第一个单元格拆分:用正则分别抓取开头的数字(ID)、日期格式的字符串,剩余部分作为文件名,确保三个字段准确分离。
- private与NotScheduled合并:先把
privateNot拆成private和临时存储的Not,之后和下一个单元格的Scheduled拼接成NotScheduled。 - 空值过滤:遇到空的单元格内容直接跳过,避免无效空元素出现在最终数组里。
- 按单元格位置处理:通过
switch根据单元格索引(位置)应用不同规则,逻辑清晰易维护。
内容的提问来源于stack exchange,提问作者Avdhut Joshi
相关产品推荐
相关产品推荐

