react-testing-library - react-testing-library - 如果文本包含在其他子 html 标记中,如何测试文本是否存在?
问题描述
给定示例html:
const fragment = (<div>Hello <span>world</span>. How are you <b>doing</b>?</div>)
有没有办法使用 react-testing-library 忽略所有子 html 标签?
像这样(伪代码)
expect(fragment).toHaveTextContent(/hello world. how are you doing/)
解决方案
第一个解决方案:
你可以使用@testing-library/jest-dom
这个库提供了一组自定义的 jest 匹配器,你可以使用它们来扩展 jest 和 react-testing-library。链接在这里:
https://github.com/testing-library/jest-dom#tocontainelement
<span data-testid="ancestor"><span data-testid="descendant"></span></span>
const ancestor = getByTestId('ancestor')
const descendant = getByTestId('descendant')
const nonExistantElement = getByTestId('does-not-exist')
expect(ancestor).toContainElement(descendant)
expect(descendant).not.toContainElement(ancestor)
expect(ancestor).not.toContainElement(nonExistantElement)
第二种解决方案:
import { render, within } from '@testing-library/react'
const { getByLabelText } = render(<MyComponent />)
const signinModal = getByLabelText('Sign In')
within(signinModal).getByPlaceholderText('Username')
推荐阅读
- javascript - 历史推送不更新新数据
- javascript - 如何在framework7中加载多个自动完成?
- go - 在 Go 中生成构建时间戳
- php - 用php和sql建表
- javascript - 将字符串(Revit 公式)转换为 JavaScript 对象
- google-play - 我的应用程序从 Play 商店中消失了......即使它仍然在开发者控制台中发布
- facebook - 如何撤销特定的 Facebook 访问令牌
- asp.net-mvc - 无法在 Angular 6 组件 templateurl 下加载 MVC 部分视图
- python - 更新未在 pygame 中注册的矩形坐标?
- php - 如何从图像元数据 php 中获取标签?