我正在尝试测试我的组件是否在我的 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/