我测试的组件呈现了以下内容:
<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/