Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在特定元素的上下文中进行Jest测试中的查询?_Javascript_Reactjs_Jestjs_React Testing Library - Fatal编程技术网

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

Javascript 如何在特定元素的上下文中进行Jest测试中的查询?,javascript,reactjs,jestjs,react-testing-library,Javascript,Reactjs,Jestjs,React Testing Library,我在开玩笑地为React应用程序编写测试。假设我有一个网页,其中包含某个元素的倍数。在下面的例子中,我有两个按钮。我想在测试中查询测试ID为2的div元素内部的按钮 有没有办法在父div的上下文中查询该按钮?比如: const secondDiv = screen.getByTestId(2); const buttonOfInterest = secondDiv.getByRole('button', {name: 'Button'}); 我以前试过上述方法,但不起作用 我知道我可以为按钮分

我在开玩笑地为React应用程序编写测试。假设我有一个网页,其中包含某个元素的倍数。在下面的例子中,我有两个按钮。我想在测试中查询测试ID为2的div元素内部的按钮

有没有办法在父div的上下文中查询该按钮?比如:

const secondDiv = screen.getByTestId(2);
const buttonOfInterest = secondDiv.getByRole('button', {name: 'Button'});
我以前试过上述方法,但不起作用

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

您可以使用“”助手功能:

import { screen, within } from '@testing-library/dom';

const someDiv = screen.getByTestId('some-id');
const childButton = within(someDiv).getByRole('button');

您可以使用“”辅助函数:

import { screen, within } from '@testing-library/dom';

const someDiv = screen.getByTestId('some-id');
const childButton = within(someDiv).getByRole('button');


除了genechk的回答之外:

如果您正在为react应用程序编写测试,最好使用

import { screen, within } from '@testing-library/react'
而不是

import { screen, within } from '@testing-library/dom';

除了genechk的回答之外:

如果您正在为react应用程序编写测试,最好使用

import { screen, within } from '@testing-library/react'
而不是

import { screen, within } from '@testing-library/dom';