嗨,我在测试组件函数处理程序时遇到了麻烦。
我有这个组件:
class MUIToolbar extends React.Component {
state = {
title: this.props.title,
anchorEl: null,
value: 0,
open: false
};
handleMenu = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ anchorEl: null });
};
handleChange = (event, value) => {
this.setState({ value });
};
homeRedirect = () => {
this.props.history.push('/groups');
}
render() {
const { classes } = this.props;
const { anchorEl, value, title } = this.state;
const open = Boolean(anchorEl);
return (
<div className={classes.root}>
<AppBar position="fixed" className={classes.root}>
<Toolbar>
<Typography variant="h6" color="inherit" className={classes.grow} onClick={this.homeRedirect}>
{title}
</Typography>
<Tabs
value={value}
onChange={this.handleChange}
classes={{ root: classes.tabsRoot, indicator: classes.tabsIndicator }}>
<Tab
classes={{ root: classes.tabRoot, selected: classes.tabSelected }}
label="Groups"
component={Link} to="/groups"/>
</Tabs>
<div>
<IconButton
aria-owns={open ? 'menu-appbar' : undefined}
aria-haspopup="true"
onClick={this.handleMenu}
color="inherit">
<AccountCircle />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={open}
onClose={this.handleClose}>
<MenuItem onClick={this.handleClose}>Profile</MenuItem>
<MenuItem onClick={this.handleClose}>Log out</MenuItem>
</Menu>
</div>
</Toolbar>
</AppBar>
<Switch>
<Route path="/groups" component={Groups} />
</Switch>
</div>
);
}
}
const enhance = compose(
defaultProps({
title: 'Daily Track',
}),
withStyles(styles),
withRouter,
);
export default enhance(MUIToolbar);
因此,我想测试handleMenu
,handleClose
,handleChange
和homeRedirect
,我这样做是这样的:
describe('Testing Toolbar component', () => {
let mount;
let shallow;
let mountWrapper;
let shallowWrapper;
let props = {};
beforeEach(() => {
props.onClick = jest.fn();
mount = createMount();
shallow = createShallow();
mountWrapper = mount(<Router><MUIToolbar /></Router>);
shallowWrapper = shallow(<MUIToolbar />);
});
it('should simulate user IconButton click.', () => {
const instance = mountWrapper.instance();
const userIconButton = shallow(<IconButton />);
userIconButton.simulate('click');
jest.spyOn(instance, 'handleMenu');
expect(instance.handleMenu).toHaveBeenCalled();
});
});
我收到此错误
Cannot spy the handleMenu property because it is not a function; undefined given instead
我尝试了很多方法来做到这一点,但我做不到。
感谢您的帮助