使用反应测试库检查文本出现在元素内部

新手上路,请多包涵

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

查询的测试库文档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 是如何工作的。我究竟做错了什么?

原文由 Hives 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 519
2 个回答

最好使用 within 来处理这类事情:

 render(<MyComponent />)
const { getByText } = within(screen.getByTestId('my-test-id'))
expect(getByText('some text')).toBeInTheDocument()

原文由 Giorgio Polvara - Gpx 发布,翻译遵循 CC BY-SA 4.0 许可协议

另一种方法来做到这一点

import {render, screen} from '@testing-library/react';

...

  render(<MyComponent />);
  expect(screen.getByTestId('my-test-id')).toHaveTextContent('some text');

请注意,现在建议使用 screen 而不是渲染结果。

(StackOverflow 将这些点发布到 KC Dobbs 文章中解释原因: react-testing-library - Screen vs Render queries

原文由 Seth McClaine 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题