gpt4 book ai didi

html - react 测试库中的父节点

转载 作者:行者123 更新时间:2023-12-03 14:36:13 25 4
gpt4 key购买 nike

我测试的组件呈现了以下内容:

<div>Text<span>span text</span></div>
事实证明,测试唯一的可靠文本是“span text”,但我想获得 <div>的“Text”部分。使用Jest和react-testing-library我可以
await screen.findByText(spanText)
这返回一个HTMLElement,但似乎受到限制,因为我在该元素周围没有任何上下文。例如,诸如parentNode和previousSibling之类的HTML方法将返回null或undefined。理想情况下,我想获取父类 <div>的文本内容。知道我如何通过Jest或react-testing-library做到这一点吗?

最佳答案

一个好的解决方案是closest函数。
closest函数的描述中写道:Returns the first (starting at element) including ancestor that matches selectors, and null otherwise.解决方案如下所示:

screen.getByText("span text").closest("div")

关于html - react 测试库中的父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62770973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com