Javascript 在功能组件中使用方法回调测试按钮
我试着用酶来测试一种反应成分。我无法测试IconButton组件上的单击,并且在模拟单击时不会调用该函数 这就是如何在外部组件上定义IconButtonJavascript 在功能组件中使用方法回调测试按钮,javascript,reactjs,unit-testing,jestjs,enzyme,Javascript,Reactjs,Unit Testing,Jestjs,Enzyme,我试着用酶来测试一种反应成分。我无法测试IconButton组件上的单击,并且在模拟单击时不会调用该函数 这就是如何在外部组件上定义IconButton var IconButton = function (props) { return (React.createElement(IconButton$1, { color: 'default', onClick: props.onClick, disabled: props.disabled, size: props.size, onM
var IconButton = function (props) {
return (React.createElement(IconButton$1, { color: 'default', onClick: props.onClick, disabled: props.disabled, size: props.size, onMouseDown: props.onMouseDown }, props.children));
};export{Button,IconButton};
这就是我在我的应用程序中使用它的方式
import React, {useState, useEffect} from 'react';
import { Drawer } from '@material-ui/core';
import ExpandLessIcon from '@material-ui/icons/ExpandLess';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import { IconButton } from '@mycomponent/button';
export default function Component1 {
const classes = useStyles();
const [open, setOpen] = useState(true);
const handleClick = function (event) {
if (event) {
setOpen(!open);
}
else {
return;
}
};
return (
<Drawer>
<div className="classname1">
<IconButton onClick={(e) => handleClick(e)} className={classes.button, "iconBtn"}>
{open ? <ExpandLessIcon data-test="lessIcon" /> : <ExpandMoreIcon data-test="moreIcon" />}
</IconButton>
</div>
</Drawer>
);
}
import React,{useState,useffect}来自“React”;
从'@material ui/core'导入{Drawer};
从“@material ui/icons/ExpandLess”导入ExpandLessIcon;
从“@material ui/icons/ExpandMore”导入ExpandMoreIcon;
从'@mycomponent/button'导入{IconButton};
导出默认函数组件1{
const classes=useStyles();
const[open,setOpen]=useState(true);
const handleClick=函数(事件){
如果(事件){
setOpen(!open);
}
否则{
返回;
}
};
返回(
handleClick(e)}className={classes.button,“iconBtn”}>
{打开?:}
);
}
下面是我模拟点击图标按钮的测试。我还尝试了另一种方法来检查handleClick是否被调用,但仍然失败
const wrapper = shallow(<Component1 />);
it('Test the button click', () => {
expect(wrapper.containsMatchingElement(<ExpandMoreIcon />)).toBeTruthy()
const element = wrapper.find(".iconBtn")
const mockEvent = {target: {}};
element.simulate('click', mockEvent)
expect(wrapper.containsMatchingElement(<ExpandLessIcon />)).toBeTruthy()
})
const wrapper=shallow();
它('测试按钮点击',()=>{
expect(wrapper.containsmatchinglement()).toBeTruthy()
常量元素=wrapper.find(“.iconBtn”)
const mockEvent={target:{};
元素。模拟('click',mockEvent)
expect(wrapper.containsmatchinglement()).toBeTruthy()
})
尝试更改此行:
const element = wrapper.find("button").at(0);
或者您可以从debug()
中通过它的类名找到它:
请注意,在这种情况下,您会模拟单击实际的html按钮。现在找不到任何节点。“方法“simulate”将在1个节点上运行。0改为。”因此,请单击您正在使用的任何库来模拟此
IconButton$1的“引擎盖下”渲染,因此它肯定是一个按钮
,您始终可以通过console.log(wrapper.debug())来调查组件
我已经修改了我的答案
const element = wrapper.find(".MuiButtonBase-root MuiIconButton-root");