Hiv*_*ves 30 javascript reactjs react-testing-library
我正在使用Testing Library为 React 应用程序编写一些测试。我想检查一些文本是否出现,但我需要检查它是否出现在特定位置,因为我知道它已经出现在其他地方。
查询的测试库文档说getByText查询需要一个container参数,我猜可以让您在该容器内进行搜索。我尝试这样做,container并text按照文档中指定的顺序使用和参数:
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)
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 查询)
小智 8
这样您就可以更加精确,专注于特定项目:
expect(queryByTestId("helperText")?.textContent).toContain("Help me!");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24236 次 |
| 最近记录: |