Cypress表格验证:文档名称一致性与最新日期排序检查
Cypress表格验证实现方案
任务1:验证「Name Document」列所有行内容完全一致
- 定位表格中「Name Document」列的所有单元格
- 获取所有单元格的文本内容
- 断言所有文本与第一个单元格的文本完全匹配
示例代码:
cy.get('table') .find('thead th') .contains('Name Document') .then(($header) => { // 获取目标列的索引(CSS选择器列数从1开始) const columnIndex = $header.index() + 1; // 获取该列所有行的文本内容 cy.get(`table tbody tr td:nth-child(${columnIndex})`) .invoke('text') .then((texts) => { // 处理文本,去除空内容与多余空格 const textArray = texts.split('\n').map(text => text.trim()).filter(Boolean); // 以第一个单元格内容为基准,断言所有内容一致 const baseValue = textArray[0]; textArray.forEach(text => { expect(text).to.equal(baseValue); }); }); });
任务2:验证「Issue Date」列的最新日期位于表格首行
- 定位「Issue Date」列的所有单元格
- 将日期文本转换为可比较的Date对象
- 找出列中的最大日期(最新日期)
- 断言首行日期与最新日期一致
示例代码:
cy.get('table') .find('thead th') .contains('Issue Date') .then(($header) => { const columnIndex = $header.index() + 1; cy.get(`table tbody tr td:nth-child(${columnIndex})`) .invoke('text') .then((texts) => { const dateTexts = texts.split('\n').map(text => text.trim()).filter(Boolean); // 将文本转为Date对象,需匹配页面实际日期格式,格式特殊可引入dayjs等库处理 const dates = dateTexts.map(dateText => new Date(dateText)); // 筛选出最新日期 const latestDate = new Date(Math.max(...dates)); // 获取首行日期并断言 const firstRowDate = new Date(dateTexts[0]); expect(firstRowDate.getTime()).to.equal(latestDate.getTime()); }); });
注意事项
- 代码中的
table选择器需根据页面实际结构调整(如添加类名、ID精准定位) - 日期转换逻辑需适配页面中「Issue Date」列的具体格式,避免解析错误
内容的提问来源于stack exchange,提问作者Blim
相关产品推荐
相关产品推荐

