gpt4 book ai didi

reactjs - 测试在按钮上呈现另一个组件单击 ReactJS

转载 作者:行者123 更新时间:2023-12-04 14:50:14 32 4
gpt4 key购买 nike

我在两个不同的文件中有两个单独的组件
组件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

});
不幸的是,我收到此错误 Receiver must be HTMLElement or SVGElementexpect(<ComponentA />).toBeInTheDocument();线
拜托,我是测试新手,我该如何解决这个问题?
谢谢您的意见

最佳答案

UI 测试旨在测试呈现的输出,而不是代码的内部结构。换句话说,你不应该测试组件是否已呈现,但您 应该测试该组件渲染的内容是否在屏幕上。
例如,如果 ComponentA呈现 h1带有文本内容“hello world”的标签,您可能想要测试该标签或文本是否在文档中。
这是一个简化的示例。
组件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();
});

关于reactjs - 测试在按钮上呈现另一个组件单击 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69209144/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com