如何使用反应测试库获取带有testid的元素?
How to get the element with the testid using react testing library?
您好,我想使用 getByTestId 访问第一个 div class "icon"。
下面是 DOM 的样子,
<div class="parent">
<div data-testid="add">
<div class="info"></div>
<div class="action">
<div class="icon"/> //want to access this
</div>
</div>
</div>
<div class="parent">
<div data-testid="add">
<div class="info"></div>
<div class="action">
<div class="icon"/>
</div>
</div>
</div>
正如您从上面看到的那样,有多个带有 testid "add" 的元素,我怎样才能获得第一个添加 div 并使用 class 图标访问其子元素 div。
我试过了
const element = queryAllByTestId('add')[0].querySelector(
'div'
)[1];
这给出了未定义的元素。
有人可以帮我解决这个问题吗?谢谢。
getAllBy*
queries return an array of all matching nodes for a query,
and throw an error if no elements match.
queryAllBy*
queries return an array of all matching nodes for a
query, and return an empty array ([]
) if no elements match.
使用查询变体以便在未找到匹配项时不进行测试,并使用 querySelectorAll 因为 querySelector
returns 只有第一个匹配的元素,或者为 null。
const element = queryAllByTestId("add");
if (element.length) {
let divs = element[0].querySelectorAll("div");
// ...get the div node you need
}
您甚至可以指定具有特定 class
的 div
const element = queryAllByTestId("add");
if (element.length) {
let divs = element[0].querySelectorAll("div.icon");
// ...get the div node you need
}
您好,我想使用 getByTestId 访问第一个 div class "icon"。
下面是 DOM 的样子,
<div class="parent">
<div data-testid="add">
<div class="info"></div>
<div class="action">
<div class="icon"/> //want to access this
</div>
</div>
</div>
<div class="parent">
<div data-testid="add">
<div class="info"></div>
<div class="action">
<div class="icon"/>
</div>
</div>
</div>
正如您从上面看到的那样,有多个带有 testid "add" 的元素,我怎样才能获得第一个添加 div 并使用 class 图标访问其子元素 div。
我试过了
const element = queryAllByTestId('add')[0].querySelector(
'div'
)[1];
这给出了未定义的元素。
有人可以帮我解决这个问题吗?谢谢。
getAllBy*
queries return an array of all matching nodes for a query, and throw an error if no elements match.
queryAllBy*
queries return an array of all matching nodes for a query, and return an empty array ([]
) if no elements match.
使用查询变体以便在未找到匹配项时不进行测试,并使用 querySelectorAll 因为 querySelector
returns 只有第一个匹配的元素,或者为 null。
const element = queryAllByTestId("add");
if (element.length) {
let divs = element[0].querySelectorAll("div");
// ...get the div node you need
}
您甚至可以指定具有特定 class
的 divconst element = queryAllByTestId("add");
if (element.length) {
let divs = element[0].querySelectorAll("div.icon");
// ...get the div node you need
}