[英]How to test react component with onClick function Jest/React testing library
I am trying to get to 100% coverage for my tests in one of them it highlights the onClick function which sets the state for a component: this is the component:我试图在其中一个测试中达到 100% 的覆盖率,它突出显示了设置组件状态的 onClick 函数:这是组件:
I have a button which has an onClick function as below, the button is mapped in from an array of objects.我有一个具有 onClick 功能的按钮,如下所示,该按钮是从一组对象映射进来的。
const [activeIdx, setActiveIdx] = React.useState(0);
<button type="button" data-testid={'btn-test}
onClick={() => {setActiveIdx(() => index); inner.cb(index)}}key={inner.id}>
{inner.title}</button>
This button clicks and sets the active index of the button clicked as this is a button group.此按钮单击并设置所单击按钮的活动索引,因为这是一个按钮组。 How would I test the onClick function in jest/react-testing library?
我将如何在 jest/react-testing 库中测试 onClick 函数?
I have some tests that check a few things like:我有一些测试可以检查一些事情,例如:
it('Should render without crashing', (): void => {
const div = document.createElement("div");
ReactDOM.render(<ButtonGroup data={Data}/>, div);
ReactDOM.unmountComponentAtNode(div);
});
const btn = screen.getByRole('button', {name: '1 hour'});
it('Should be clicked', (): void => {
fireEvent.click(btn);
expect(btn).toBeValid();
});
But how to mock the function and check that?但是如何模拟函数并检查它呢?
This actually goes against the core idea of testing library where这实际上违背了测试库的核心思想,其中
Testing Library encourages you to avoid testing implementation details like the internals of a component
测试库鼓励您避免测试实现细节,例如组件的内部结构
There are two solutions you can try:您可以尝试两种解决方案:
onClick
then within the test you can mock that function to see if it was called, what was returned, etc.onClick
使用的函数,然后在测试中您可以模拟该函数以查看它是否被调用、返回了什么等。你可以用 Enzyme 模拟点击,这里有一个关于它的博客https://preactjs.com/guide/v10/unit-testing-with-enzyme/ 。
wrapper.find('btn').simulate('click');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.