我测试的组件呈现如下内容:
<div>Text<span>span text</span></div>
事实证明,测试我拥有的唯一可靠文本是“跨度文本”,但我想获取 <div>
的“文本”部分。使用 Jest 和 react-testing-library 我可以
await screen.findByText(spanText)
这将返回一个 HTMLElement 但它似乎受到限制,因为我没有元素周围的任何上下文。例如 parentNode 和 previousSibling 等 HTML 方法返回 null 或 undefined。理想情况下,我想获取父级的文本内容 <div>
。知道如何使用 Jest 或 react-testing-library 做到这一点吗?
原文由 Kevin Burton 发布,翻译遵循 CC BY-SA 4.0 许可协议
一个很好的解决方案是
closest
功能。在closest
函数的描述中写道:Returns the first (starting at element) including ancestor that matches selectors, and null otherwise.
解决方案如下所示: