javascript - 使用反应测试库检查文本是否出现在元素内
问题描述
我正在使用Testing Library为 React 应用程序编写一些测试。我想检查是否出现了一些文本,但我需要检查它是否出现在特定位置,因为我知道它已经出现在其他地方。
查询的测试库文档说getByText
查询需要一个container
参数,我猜它可以让您在该容器中搜索。我尝试这样做,并按照文档中指定的顺序使用container
and参数:text
const container = getByTestId('my-test-id');
expect(getByText(container, 'some text')).toBeTruthy();
我得到一个错误:matcher.test is not a function
。
如果我把参数反过来:
const container = getByTestId('my-test-id');
expect(getByText('some text', container)).toBeTruthy();
我得到一个不同的错误:Found multiple elements with the text: some text
这意味着它不在指定的容器内搜索。
我想我不明白它是如何getByText
工作的。我究竟做错了什么?
解决方案
最好within
用于此类事情:
const { getByTestId } = render(<MyComponent />)
const { getByText } = within(getByTestId('my-test-id'))
expect(getByText('some text')).toBeInTheDocument()
推荐阅读
- android - 调用了 Admob onAdLoaded 但屏幕上没有显示任何内容
- node.js - 前端服务器(Node JS 和 Angular JS)与后端服务器(.NET API)之间的连接
- sql - 以锯齿模式选择最大值(局部最大值)
- haskell - 有没有办法在 Yesod 中使用 defaultLayout 和源(管道)
- deployment - Solidity 迁移合同试运行与真实
- jenkins - 在 Jenkinsfile shell 中转义 JSON 字符串
- java - Thread#run() 中的 Thread#wait() 和 JFrame#keyPressed() 中的 Thread#notify() - 我的实现线程安全吗?
- youtube - Youtube 播放列表 api 返回部分数据
- php - 使用 Cakephp 3.6 定义 cron 作业
- hyperledger-fabric - 是否有一些好的文档或文章来获取有关如何动态识别 Hyper ledger Peers IP 的信息