我在两个不同的文件中有两个单独的组件
组件 A和组件 B
我在组件 B中有一个按钮
现在我想测试一下,当单击组件 B中的特定按钮时,组件 A应呈现如下:
import { render, screen, fireEvent } from '@testing-library/react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB'
test('Component A Comes up on Click of Component B button', () => {
render(<ComponentB />);
const componentBButton = screen.getByRole('button');
fireEvent.click(componentBButton);
expect(<ComponentA />).toBeInTheDocument(); //This throwing an error that receiver must be HTMLElement or SVGElement
});
不幸的是,我在expect(<ComponentA />).toBeInTheDocument();
行上Receiver must be HTMLElement or SVGElement
收到此错误
拜托,我是测试新手,我该如何解决这个问题? 感谢您的投入
UI 测试旨在测试呈现的输出,而不是代码的内部结构。换句话说,您不应该测试组件是否已呈现,而应该测试该组件呈现的内容是否在屏幕上。
例如,如果ComponentA
呈现一个包含文本内容"hello world"的h1
标签,您可能希望测试该标签或文本是否在文档中。
下面是一个简化的示例。
组件 A
const ComponentA = () => <h1>hello world</h1>
组件B
const ComponentB = () => (
<div>
<p>My App</p>
<ComponentA />
</div>
);
测试
test('hello world is rendered to the screen', () => {
render(<ComponentB />);
// Asserts that the HTML ComponentA produces was actually rendered
expect(screen.findByText('hello world')).toBeInTheDocument();
});
expect
函数只能是 DOM 元素而不是 React 组件。
您可以通过在fireEvent.click(componentBButton)
调用后识别文档中来检查文档中是否有<ComponentA>
。它是否具有id
或任何其他唯一属性?
让我们想象一下,以下是<ComponentA>
的定义:
const ComponentA = () => {
return (
<div id="component_a">Hello World</div>
);
}
我们现在可以使用component_a
id 来识别它,并将其传递给我们的expect
函数:
expect(document.getElementById("component_a")).toBeInTheDocument();