我有一个包含 6 列和可变行的表格。现在我想让 cypress 测试删除按钮。所以我在之前的测试中在我的表中创建了一个测试项,并希望我的程序删除这个测试项。
如何使用 cypress 在第 2 列的表格中搜索、过滤行并单击第 6 列中的按钮?
我阅读了 cypress.io 上的文档和指南,但没有找到任何解决方案。
<div class="row">
<div class="top-buffer"></div>
<div class="panel panel-primary">
<div class="panel-heading panel-head">Article</div>
<div class="panel-body">
<div class="btn-group">
<a asp-action="Edit" asp-route-id="@Guid.Empty" class="btn btn-primary"><i class="" glyphicon glyphicon-plus"></i>NEW</a>
</div>
<div class="top-buffer"></div>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
@foreach (var att in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => att.1)</td>
<td>@Html.DisplayFor(modelItem => att.2)</td>
<td>@Html.DisplayFor(modelItem => att.3)</td>
<td>@Html.DisplayFor(modelItem => att.4)</td>
<td>@Html.DisplayFor(modelItem => att.5)</td>
<td>
<a asp-action="Edit" asp-route-id="@att.Id" class="btn btn-info"><i class="glyphicon glyphicon-pencil"></i>EDIT</a>
<a asp-action="DeleteCategory" asp-route-id="@att.Id" class="btn btn-danger"><i class="glyphicon glyphicon-trash"></i>DELETE</a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
您显示的代码是在服务器上编译的 ASP.Net 源代码,因此浏览器中的 HTML(您的测试需要使用的 HTML)会有所不同。
即
@foreach (var att in Model)
为模型中的每个项目提供一行,@Html.DisplayFor(modelItem => att.2)
将转换为第 2 列的一些具体内容。
因此,如果您在浏览器中运行应用程序并从控制台复制并粘贴该 HTML,那么答案会更容易。
由于您想在第 2 列中搜索,因此可以采用两种方式。
如果第2列中的内容非常独特,例如未出现在其他列中的名称,您只需查找文本即可定位它
cy.contains('td', 'text-to-search-for') // gives you the cell
.parent() // gives you the row
.within($tr => { // filters just that row
.get('td a') // finds the buttons cell of that row
.contains('DELETE') // finds the delete button
.click()
或
cy.contains('td', 'text-to-search-for') // gives you the cell
.siblings() // gives you all the other cells in the row
.contains('a', 'DELETE') // finds the delete button
.click()
如果您要搜索的文本可以出现在第 2 列以外的列中,则会变得更加困难,但很可能上述内容就足够了。
需要注意的另一件事是,如果您的测试场景始终使用相同的数据(例如来自固定文件的数据),您可以针对特定的行号,但这是一个“脆弱的测试”,如果页面结构发生变化,则需要重新编写。
cy.get('.btn').click
我打赌这会在以后引起问题,因为你可能会有更多的行。
cy.get('table').find('tr').eq(ROW INDEX).find('td').eq(COLUMN INDEX).find('.btn-danger').click()
现在我认为这不是最好的方法。我建议您在代码中添加一些类,以便您可以更轻松地访问元素。例如,向删除按钮添加一个类,即 class="delete-item",这样您就可以在选择器中使用它
cy.get('table').find('tr').eq(ROW INDEX).find('td').eq(COLUMN INDEX).find('.delete-item').click()
我对这个答案不是100%确定,因为我没有尝试过。
您可以将 data-testid 添加到删除按钮,然后只需使用以下命令找到它:
cy.get("[data-testid='YOUR TEST ID HERE']").eq(0).click()
这更像是第一个。您可以向每行删除按钮添加动态数据测试id。这可以在 @foreach 部分轻松完成。使用循环中的索引,您可以添加数据测试ID作为
YOUR-DATA-TEST-ID-${index}
。
然后选择cy.get(`[data-testid='YOUR-TEST-ID-${index}']`).click()