首页 > 解决方案 > 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/)

标签: react-testing-library

解决方案


第一个解决方案:

你可以使用@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')

推荐阅读