html - react 测试库中的父节点

标签 html jestjs react-testing-library

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

<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/

相关文章:

javascript - 我可以在用户单击链接后操作 DOM 吗?

reactjs - Jest 测试中的 `requestAnimationFrame` polyfill 错误

reactjs - 使用 React-Virtualized AutoSizer 时,子项未在测试中呈现

html - 为什么 100% 的输入宽度总是超出包含的 div?

javascript - 如何单击按钮以获取具有反应的组件之一

javascript - Jest 测试经常失败,因为 Puppeteer 无法点击 DOM 中的元素

reactjs - React - 当父组件将方法作为 prop : parent or child component? 传递时,在哪里进行单元测试状态更改

javascript - React 测试库 waitForElementToBeRemoved 无法正常工作

html - 如何使我的标题图像以全高显示而不向其中的元素添加填充?

typescript - Jest : I want to put test code under 'Project/test/' directory, 但发生配置错误