react-testing-library 为什么要使用测试 id

react-testing-library why use test id

我正在使用反应测试库。在文件中说

Note that using this as an escape hatch to query by class or id is a bad practice because users can't see or identify these attributes. Use a testid if you have to.

我想知道为什么这是一种不好的做法。我不想用 data-testid 乱丢我的代码。我的组件中已经有 ids 和 classNames。为什么不推荐使用它们?

谢谢。

好问题。从表面上看,这似乎没有多大意义,因为用户也看不到或识别睾丸。

我会说这归结为将影响降到最低。如果您的测试代码通过 class 或 id 查询,其他开发人员更有可能复制它而不是 testid 用法,这仅仅是因为您必须向组件添加 testids,如您所见,这不会感觉不错。使用 testid 表示 "I have no good options here, I'm forced to do this".

react-testing-library 主要用于黑盒功能测试。使用特定于实现的选择器可能意味着测试测试的是实现而不是用户可以观察到的行为。虽然使用 data-testid 表示它是明确的并且是故意添加的以便于测试,而选择器可能是模糊的并且在实现更改时被意外更改。

这并不意味着如果常规选择器已经达到目的,则不应使用它们,只要开发人员不使用它们来测试功能测试中的实现即可。

这也不意味着 react-testing-library 不能用于测试隔离单元测试中的实现。它实际上可以,但它缺少必要的功能,因此与为此设计的 Enzyme 相比,这会产生大量样板代码。