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

标签 javascript reactjs jestjs react-testing-library

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

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

export default Title;
这是我的测试文件,它试图检查我的组件是否显示“MY RTL PROJECT”。
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"只能在工作人员内部使用
  ● 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')
就是说——你是通过文本获取一个元素,然后验证它是否包含你刚刚用来查询它的文本,所以这个测试可能没有很高的值(value)。验证它是否存在可能更有意义:
const titleValue = getByText('MY RTL PROJECT')
expect(titleValue).toBeInTheDocument();
...也来自 jest-dom .
另外,虽然我不能肯定地说,aria-label 的用法将与标题包含的文本不同的文本应用于标题对我来说似乎是可疑的——您可能想要验证这并不代表可访问性反模式。

关于javascript - 如何获取 H1 标签的值并使用 Jest 和 RTL 对其进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67630376/

相关文章:

javascript - jQuery 自动完成将结果标签显示为未定义

reactjs - React - 激活 onClick 函数会引发 'Cannot read property' 错误

typescript - 开 Jest mock TypeScript 类 "No overload expects 1 type arguments"

javascript - 使用 Truffle 测试 Solidity 合约中的事件

javascript - JQuery悬停下拉菜单在悬停在下拉菜单上时消失

reactjs - Material-UI Data-Grid : How pass parameter to custom toolbar?

typescript - 更新到 27 后,Angular jest 无法理解导入路径

reactjs - 测试在 React 功能组件中使用 ref 添加的鼠标事件监听器

javascript - Uncaught ReferenceError : rgba is not defined

javascript - 单元测试 ReactJS 组件产生不变违规 : findComponentRoot