如何使用 Jest 和 RTL 获取 H1 标签的值并进行测试

How to get the value of H1 tag and test it using Jest and RTL

我正在尝试测试我的组件是否在我的 h1 中显示正确的值。

下面是我要测试的组件。

  const Title = () => {
  return (
    <>
      <h1 aria-label='Title of the project'>MY RTL PROJECT</h1>
    </>
  );
};

export default Title;

这是我的测试文件,它试图检查我的组件是否显示“我的 RTL 项目”。

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


    describe('Checks the title component', () => {
    
        it('checks the value of the Title component', () => {
            const { getByText } = render(<Title />);
            const titleValue = getByText('MY RTL PROJECT')
            expect(titleValue).toBe('MY RTL PROJECT')
        })
    })

这里是错误:"messageParent" can only be used inside a worker

  ● Checks the title component › checks the value of the Title component

expect(received).toBe(expected) // Object.is equality

Expected: "MY RTL PROJECT"
Received: <h1 aria-label="Title of the project">MY RTL PROJECT</h1>

这一行:

const titleValue = getByText('MY RTL PROJECT')

...返回给您的是一个元素,而不是该元素包含的文本。所以代替这一行:

expect(titleValue).toBe('MY RTL PROJECT')

...您可能想使用 jest-dom toHaveTextContent():

expect(titleValue).toHaveTextContent('MY RTL PROJECT')

就是说——您是通过文本获取一个元素,然后验证它是否包含您刚刚用于查询它的文本,因此该测试的价值可能不是很高。验证它是否存在可能更有意义:

const titleValue = getByText('MY RTL PROJECT')
expect(titleValue).toBeInTheDocument();

...也来自 jest-dom.

此外,虽然我不能肯定地说,使用 aria-label 将文本应用于您的标题而不是标题包含的文本对我来说似乎很可疑 - 您可能想要验证不代表可访问性 anti-pattern.