如何在 Jest 测试中在特定元素的上下文中进行查询?

Eri*_*ric 6 javascript reactjs jestjs react-testing-library

我正在 Jest 中为 React 应用程序编写测试。假设我有一个网页包含多个特定元素。在下面的例子中,我有两个按钮。我想在测试中查询测试 ID 为 2 的 div 元素内部的按钮。

有没有办法让我在该父 div 的上下文中查询该按钮?就像是:

const secondDiv = screen.getByTestId(2);
const buttonOfInterest = secondDiv.getByRole('button', {name: 'Button'});
Run Code Online (Sandbox Code Playgroud)

我之前已经尝试过上面的方法,但它不起作用。

我知道我可以将测试 ID 分配给按钮,但我认为在其他场景中能够在特定元素的上下文中进行查询(而不是使用screen,它引用整个文档)会非常有帮助。

在此输入图像描述

gen*_*chk 8

您可以在 \xe2\x80\ x9d辅助函数中使用 \xe2\x80\x9c :

\n
import { screen, within } from \'@testing-library/dom\';\n\nconst someDiv = screen.getByTestId(\'some-id\');\nconst childButton = within(someDiv).getByRole(\'button\');\n\n
Run Code Online (Sandbox Code Playgroud)\n