Skip to content

Cypress - Web 表格

Cypress 可以有效地与 HTML Web 表格(Web tables)进行交互,无论它们是静态的(固定行和列)还是动态的。理解表格结构是自动化交互的关键。

在 HTML 中,表格通常由 <table>、<thead>、<tbody>、<tr>(表格行)、<th>(表头)和 <td>(表格数据/单元格)标签构成。

  • 访问表格主体内的所有行:cy.get('tbody tr') 或更具体的选择器,例如 cy.get('#myTableId tbody tr')。

  • 访问行内的所有单元格(列):cy.get('tbody tr td')。

  • 访问特定列中的单元格(例如,第二列):cy.get('tbody tr td:nth-child(2)')。请注意,nth-child 是从 1 开始索引的。

  • 要迭代遍历行或单元格,.each() 命令非常有用。

Cypress 还提供了 .next() 等命令来获取紧随其后的同级元素(sibling element),以及 .prev() 来获取紧邻的前一个同级元素。这些命令对于在行内的单元格之间导航很有用。.parent() 命令可用于向上获取包含该元素的行,而 .find() 可用于在特定行或单元格内定位元素。

典型的 HTML 表格结构可能如下所示:

<table>
<thead>
<tr>
<th>Automation Tool</th>
<th>Type</th>
<th>License Cost</th>
</tr>
</thead>
<tbody>
<tr>
<td>Selenium</td>
<td>Open Source</td>
<td>Free</td>
</tr>
<tr>
<td>Cypress</td>
<td>Open Source</td>
<td>Free (Dashboard is paid)</td>
</tr>
<!-- ... more rows ... -->
</tbody>
</table>

让我们考虑一个场景:我们想找到第一列(‘AUTOMATION TOOL’)中包含 ‘Selenium’ 的行,然后验证第二列(‘TYPE’)中对应的内容是 ‘Open Source’。我们将使用位于 https://sqengineer.com/practice-sites/practice-tables-selenium/ 的表格(表格 ID: table1)。

目标网页显示了一个包含 ‘Automation Tool’、‘Type’、‘Link’ 等列的表格。

以下是使用 Cypress 实现此验证的示例:

describe('Web Table Interaction', () => {
it('Verifies cell content based on another cell in the same row', () => {
cy.visit('https://sqengineer.com/practice-sites/practice-tables-selenium/');
// Target the first column (Automation Tool) of table with id 'table1'
// 定位 id 为 'table1' 的表格的第一列(Automation Tool)
cy.get('#table1 tbody tr td:nth-child(1)').each(($cell, index) => {
const toolName = $cell.text();
if (toolName.includes('Selenium')) {
// If 'Selenium' is found, get the corresponding cell in the second column (Type)
// 如果找到 'Selenium',则获取同一行的第二列(Type)中对应的单元格
cy.get('#table1 tbody tr').eq(index) // Get the current row // 获取当前行
.find('td:nth-child(2)') // Find the second cell in that row // 查找该行中的第二个单元格
.then(($typeCell) => {
const typeValue = $typeCell.text();
// Assert that the type is 'Open Source'
// 断言类型是 'Open Source'
expect(typeValue.trim()).to.equal('Open Source');
});
}
});
});
});

此测试运行时:

  • Cypress 访问指定的 URL。
  • 它遍历 #table1 的第一列中的每个单元格。
  • 当它找到包含 ‘Selenium’ 的单元格时,会查找同一行中的第二个单元格(td:nth-child(2))。
  • 它提取第二个单元格的文本,并断言其等于 ‘Open Source’。

Test Runner 日志将显示执行的命令,包括迭代过程以及数据匹配时的成功断言。如果在 ‘Selenium’ 对应的行中未找到 ‘Open Source’,断言将失败。

  • 为你的表格使用特定的选择器(例如,通过 ID 或 data-cy 属性),以避免页面上存在多个表格时的歧义。
  • 在迭代时,.parent() 和 .find() 命令对于精确定位相对于当前迭代元素的其他元素非常有用。
  • 对于复杂的表格,可以考虑创建自定义命令(custom commands)或辅助函数(helper functions)来封装常见的表格操作。