如何检查 react-testing-library 中的级别?

How to check for level in react-testing-library?

我在页面上有一个标题 <h4>Big offer!</h4>,当我第一次 运行 我的测试时,我得到了:

Expected: "Big offer!"
Received: <h4>Big offer!</h4>

  35 |     const switchToggle = screen.getByRole('checkbox');
  36 |     expect(switchToggle.checked).toEqual(true);
> 37 |     expect(titleEl).toEqual(title);

好的,它得到了正确的文件,所以我更改了我的代码以实际检查标题级别和文本,但它失败了:

Expected: "Big offer!"
Received: undefined

  35 |     const switchToggle = screen.getByRole('checkbox');
  36 |     expect(switchToggle.checked).toEqual(true);
> 37 |     expect(titleEl.name).toEqual(title);
     |                          ^
  38 |     expect(titleEl.level).toEqual(4);

我一直以为.name等于getByText()。我注释掉一行并尝试检查级别,但它再次失败:

Expected: 4
Received: undefined

  36 |     expect(switchToggle.checked).toEqual(true);
  37 |     //expect(titleEl.name).toEqual(title);
> 38 |     expect(titleEl.level).toEqual(4);

我不明白为什么我的测试用例失败了。测试代码是:

const title = 'Big offer!';
render(<Component title={title}/>);
const titleEl = screen.getByRole('heading');
expect(titleEl).toEqual(title);
expect(titleEl.level).toEqual(4);

它不会工作,因为 screen.getByRole(或其他查询)returns 一个 HTMLElement(在你的例子中 returns 一个 HTMLHeadingElement 继承了 HTMLElement).而且它没有 namelevel 属性。您可以查看更多 here.

要检查呈现的文本,您应该使用:

expect(titleEl).toHaveTextContent(title);

对于 h4 类型检查,您只需要在查询时过滤它:

const titleEl = screen.getByRole('heading', { level: 4 });

完整测试:

it('test search input', async () => {
    const title = 'Big offer!';

    render(<SearchBox title={title} />);

    const titleEl = screen.getByRole('heading', { level: 4 });

    expect(titleEl).toBeInTheDocument();
    expect(titleEl).toHaveTextContent(title);
});