如何用Cypress测试表格中标题是否归属正确分类?
如何在Cypress中验证表格标题是否属于对应分类?
在Cypress测试场景中,表格同一列混合了分类名称与标题名称,目前已实现同行标题对应值的测试,但需要验证标题是否归属正确分类。
现有同行值匹配测试代码
cy.get('.table1 > tbody > tr:nth-child(2) > td:nth-child(1)').each(($e1, index, $list) => { var titeltext=$e1.text() if(titeltext.includes('title 1')) { cy.get('.table1 > tbody > tr:nth-child(2) > td:nth-child(3)').eq(index).then(function(aValue) { var theValue = aValue.text() expect (theValue.trim()).to.equal('value1') }) } })
表格结构
<table border="1"> <tr> <td>category 1</td> <td> </td> <td> </td> </tr> <tr> <td>title 1</td> <td>subtitle 1</td> <td>value 1</td> </tr> <tr> <td>category 2</td> <td> </td> <td> </td> </tr> <tr> <td>title 2</td> <td>subtitle 2</td> <td>value 2</td> </tr> <tr> <td>title 3</td> <td>subtitle 3</td> <td>value 3</td> </tr> <tr> <td>category 3</td> <td> </td> <td> </td> </tr> <tr> <td>title 1</td> <td> </td> <td>value 4</td> </tr> <tr> <td>title 4</td> <td>subtitle 4</td> <td>value 5</td> </tr> <tr> <td>category 4</td> <td> </td> <td> </td> </tr> <tr> <td>title 5</td> <td> </td> <td>value 6</td> </tr> </table>
验证标题所属分类的两种方案
方案一:遍历行记录当前分类
通过遍历所有表格行,实时更新当前所在的分类,当遇到目标标题时直接校验所属分类:
// 定义要验证的标题和预期分类 const verifyItem = { title: 'title 2', expectedCategory: 'category 2' }; let currentCategory = ''; cy.get('.table1 > tbody > tr').each(($row) => { const firstCellText = $row.find('td:first').text().trim(); // 识别分类行,更新当前分类 if (firstCellText.startsWith('category')) { currentCategory = firstCellText; } // 识别目标标题行,校验分类是否匹配 else if (firstCellText === verifyItem.title) { expect(currentCategory).to.equal(verifyItem.expectedCategory); } });
方案二:定位标题后向上查找最近分类
先定位到目标标题所在行,再向上查找最近的分类行,直接验证分类文本:
cy.get('.table1 > tbody > tr') .contains('td:first', 'title 2') // 找到包含目标标题的行 .prevUntil('tr:contains("category")') // 向上遍历直到遇到分类行 .prev() // 获取最近的分类行 .find('td:first') .invoke('text') .should('equal', 'category 2');
内容的提问来源于stack exchange,提问作者pixelhead
相关产品推荐
相关产品推荐

