我正在尝试使用酶来测试react组件。我无法测试IconButton组件上的点击,并且当我模拟点击时,函数不会被调用。
这就是在外部组件上定义IconButton的方式。
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>
);
}这是我用来模拟点击图标按钮的测试。我还尝试了另一种方法来检查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()
})发布于 2020-12-31 19:17:14
尝试更改此行:
const element = wrapper.find("button").at(0);或者你可以通过来自debug()的className找到它
const element = wrapper.find(".MuiButtonBase-root MuiIconButton-root");请注意,在这种情况下,您将模拟单击实际的html按钮。
https://stackoverflow.com/questions/65515807
复制相似问题