如何通过数据测试搜索? (不是数据测试)
当我导入这样的屏幕对象时,
import { render, screen } from '@testing-library/react';
它允许我发出以下命令:screen.findbytestid(...)
,但是如何通过data-Test
(不是)搜索data-testid
)?尝试通过自定义属性进行搜索,但是screen> screen> scoper
中没有findbyattribute
方法。
When I import screen object like this
import { render, screen } from '@testing-library/react';
it allows me to issue the following command: screen.findByTestId(...)
, but how can I search by data-test
(not data-testid
)? Tried to search by custom attribute, but there was no findByAttribute
method in screen
either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您有机会看到该文件吗?
https://testing-library.com/docs/docs/domdocs/dom dom -testing-library/api-custom-queries/
如果您想使用自己的定义属性查询,则可以使用
build Querenqueries
制作一个,您可以在附件的文档中找到更多。
Have you had a chance to see the the document?
https://testing-library.com/docs/dom-testing-library/api-custom-queries/
If you want to query with your own-defined attribute, you can make one using
buildQueries
You can find more in the attached document.
尽管接受的答案有效,但在测试中更新全局
testIdattribute
的推荐方法是:这样,您可以继续使用
screen.findbytestid(...)
而无需定义和维护任何自定义查询。您可以使用setupfilesafterenv
在全局嘲笑上进行每个测试或全球应用程序执行此操作。这样的例子是这样的:
jest.config.ts
jest-setup.ts
While the accepted answer works, the recommended way to update the global
testIdAttribute
across tests is:This way, you can continue using
screen.findByTestId(...)
without defining and maintaining any custom query. You can do this per test or globally per app on your global jest config using thesetupFilesAfterEnv
.An example of this would look like this:
jest.config.ts
jest-setup.ts
根据文档,您可以使用手动查询
首先,您需要,您需要要获取渲染所在的容器。
然后通过您的属性搜索它。
但是您应该记住,这种方法与React测试库的意识形态相矛盾,该库说用户无法通过属性导航您的应用程序。
According to the documentation, you can use Manual Queries
First, you need to get the container where the rendering was.
Then search inside of it by your attribute.
But you should remember this approach contradicts the ideology of React Testing Library, which says User cannot navigate your application by attributes.