React-testing-library 或 Cypress - 添加多个数据测试 ID

Sho*_*ota 3 javascript jestjs cypress react-testing-library

我有一个可选择的框,因此我想为该框添加两个测试 ID,一个用于测试框的类型,另一个用于测试框是否被选中。我应该在一个 data-testid 中添加两个 data-testid 属性还是两个关键字?当涉及到 Cypress 或 React-testing-library 时,最佳实践是什么?

<div data-testid="box-user" data-testid="box-user-active">
Run Code Online (Sandbox Code Playgroud)

<div data-testid="box-user box-user-active">
Run Code Online (Sandbox Code Playgroud)

我知道还有其他方法可以检查该框是否被选中,但是还有很多其他用例,添加两个测试 ID 会让事情变得更容易。

小智 5

我已经看过帖子data-testidgetByTestId应该是最后的手段(更喜欢getByTextgetByRole),并且对此有很多意见。

从纯粹的技术角度来看,给定一个以空格分隔的值列表

<div data-testid="box-user box-user-active">
Run Code Online (Sandbox Code Playgroud)

您可以使用部分匹配表达式按任一值进行选择。参考jQuery 属性选择器

对于多个空格分隔值最有用的是~=.

cy.get('[data-testid*="box-user"]')        // either attribute
                                           // plus other variations like "unbox-user"

cy.get('[data-testid~="box-user"]')        // space-delimited (full values only)
                                           // so "box-user" but not "box-user-active"

cy.get('[data-testid~="box-user"][data-testid~="box-user-active"]') // must have both

cy.get('[data-testid^="box-user"]')          // starts with "box-user"
cy.get('[data-testid$="box-user-active"]')   // ends with "box-user-active"
Run Code Online (Sandbox Code Playgroud)