使用Reaction测试库检查出现在元素内的文本 [英] Checking text appears inside an element using react testing library

查看:0
本文介绍了使用Reaction测试库检查出现在元素内的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Testing Library为Reaction应用程序编写一些测试。我想检查某些文本是否出现,但我需要检查它是否出现在特定位置,因为我知道它已经出现在其他位置。

Testing Library documentation for queries表示getByText查询接受container参数,我猜该参数允许您在该容器内进行搜索。我尝试这样做,按照文档中指定的顺序使用containertext参数:

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()

这篇关于使用Reaction测试库检查出现在元素内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆