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

Hiv*_*ves 30 javascript reactjs react-testing-library

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

查询测试库文档getByText查询需要一个container参数,我猜可以让您在该容器内进行搜索。我尝试这样做,containertext按照文档中指定的顺序使用和参数:

const container = getByTestId('my-test-id');
expect(getByText(container, 'some text')).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:matcher.test is not a function

如果我把参数反过来:

const container = getByTestId('my-test-id');
expect(getByText('some text', container)).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)

我得到一个不同的错误: Found multiple elements with the text: some text

这意味着它不在指定的容器内搜索。

我想我不明白是如何getByText工作的。我究竟做错了什么?

Gio*_*Gpx 38

最好within用于此类事情:

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

  • 这不应该是文档中可接受的答案:“避免从‘render’结果解构查询,而是使用‘screen.getByTestId’” (9认同)

Set*_*ine 21

另一种方法来做到这一点

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

...

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

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

(StackOverflow 将要点发布到 KC Dobbs 文章解释原因:react-testing-library - Screen vs Render 查询

  • 您可能需要添加 `import "@testing-library/jest-dom/extend-expect";` 来访问 `toHaveTextContent` 匹配器,如[此处](https://github.com/testing-library/react-测试库/问题/379)。 (6认同)
  • 这很简单,对我来说非常有效:) 谢谢 (2认同)
  • 似乎是一个比接受的答案更好的解决方案,它强制采用特定的编码风格。 (2认同)

小智 8

这样您就可以更加精确,专注于特定项目:

expect(queryByTestId("helperText")?.textContent).toContain("Help me!");
Run Code Online (Sandbox Code Playgroud)