为什么选择元素时优先使用data- *属性而不是普通ID属性? [英] Why is data-* attributes preferred for element selection over a plain ID attribute?
问题描述
Cypress 和许多其他有关测试的帖子Web应用程序建议使用像 data-cy
或 data-test-id
这样的数据属性来定位元素,而不是依靠 id
属性.
Cypress and many other posts around testing web applications suggest relying on a data attribute like data-cy
or data-test-id
for locating elements rather than relying on the id
attribute.
我的理解是,有两个原因:
My understanding is that for two reasons:
- 现代的组件重用方式可以导致拥有多个相同类型的组件,并且可以在同一页面上导致多个
ID
-但这也应适用于"data-cy"或"data-test-id"属性. - 将
ID
绑定到CSS
时,倾向于更频繁地更改它们,而data-*
属性可能不那么容易更改
- The modern way of re-using the components can lead to having multiple components of the same type and can lead to multiple of those
IDs
on the same page - But this should also apply to the 'data-cy' or 'data-test-id' attributes. - When
IDs
are tied toCSS
, there's a tendency to change them more often whiledata-*
attributes may be less prone to change.
有人可以进一步介绍一下建议吗?
Can someone please throw more light on the recommendation?
我正在考虑的另一件事是请求我的开发人员将 data-test *
属性放置在会消耗组件的 div
标记上-这样测试属性实际上是组件 id
属性之上的一级,即使在使用同一组件的多个实例的情况下,它也可能派上用场.但是同样,我不确定为什么与 data-test *
属性相比,该 div
标记的 id
属性是错误的.>
The other thing I am considering is to request my devs to place the data-test*
attributes on a div
tag that would consume the component - that way the test attribute is actually one level above the component id
attribute and may come handy even in cases where multiple instances of the same component are used. But again, I am not sure why the id
attribute for that div
tag is bad when compared to the data-test*
attribute.
推荐答案
According to the official documentation, tt's best practices to use data-
attributes for selecting elements for the following reasons:
classes & IDs are highly brittle selectors that are subject to change.
data-*
属性可为选择器提供上下文,并将其与 CSS
或 JS
更改隔离.
data-*
attributes to provide context to your selectors and isolate them from CSS
or JS
changes.
想象一下,您(或另一个开发人员)正在重构代码库的一部分.您可以放心地更改 ID
或 classes
,因为它们不会破坏您现有的测试.
Imagine that you (or another dev) are refactoring a part of the codebase. You can confidently change the IDs
or classes
knowing it won't break your existing tests.
但是,您可以在重构中保留或移植 data-*
选择器,因为它不会影响代码或应用程序的行为.
However, you can keep or port your data-*
selectors in your refactoring since it won't affect your code or app's behavior.
此外,该应用程序还具有 classes
&动态更改的 ID
,这可能会导致测试不稳定或意外失败.
Also, the application has classes
& IDs
that dynamically change which can cause flaky tests or unexpected failures.
没有理由不使用 data-*
属性,除非您无权访问源代码以在其中添加这些选择器.
There is no reason not to use data-*
attributes except if you don't have access to the source code to add those selectors in.
这篇关于为什么选择元素时优先使用data- *属性而不是普通ID属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!