使用Jest测试要调用的组件的onClose事件 [英] Testing onClose event from a component to be called using jest
问题描述
我正在使用笑话和酶对反应成分进行测试,但还没有弄清楚如何从material-ui菜单中测试onClose事件.其他组件也应如此,但是出于这个问题,我们可以坚持使用菜单. 这是我的组件:
I am doing tests for a react component using jest and enzyme and haven't figured out how to test the onClose event from the material-ui Menu. Same should apply to other components but we can stick with the Menu for the sake of this question. Here it is my component:
import { Menu, MenuItem } from "@material-ui/core";
export class ItemPreviewerPage extends React.Component<ComponentProps, ComponentState> {
constructor(props) {
super(props);
this.state = {
anchorEl: undefined,
fieldsetMenu: undefined,
isColumnSelectorOpen: false,
};
}
render() {
const { classes } = this.props;
const moreMenuOpen = Boolean(this.state.anchorEl);
return (
<Menu className={classes.cardMenu}
id="long-menu"
anchorEl={this.state.anchorEl}
open={moreMenuOpen}
onClose={() => this.handleClose()}
PaperProps={{
style: {
maxHeight: 48 * 4.5,
width: 200
}
}}>
</Menu>
);
}
}
对于测试,我期望如果将anchorEl的状态设置为true,然后设置为false,则菜单将关闭.
and for the test, I was expecting the Menu to be closed if I set the state of the anchorEl to true and then to false.
it("Calls the handleClose when the Menu is closed", () => {
const props = initialProps;
const wrapper = shallow(<ItemPreviewerPage {...props} />);
const spy = jest.spyOn(wrapper.instance(), "handleClose");
wrapper.setState({ anchorEl: true });
wrapper.instance().forceUpdate();
wrapper.setState({ anchorEl: false });
wrapper.instance().forceUpdate();
expect(spy).toBeCalled();
});
怎么了?如何测试onClose?
What's wrong? How can I test the onClose?
推荐答案
我想出了如何对其进行测试. setState不会直接影响行为,我需要使用带有close参数的Simulation函数:
I figured out how to test it. The setState doesn't affect the behaviour directly, I needed to use the simulate function with the close argument:
it("Calls handleClose when menu is closed", () => {
const props = initialProps;
const tree = shallow(<ItemPreviewerPage {...props} />);
tree.find(Menu).simulate("close");
expect(props.handleClose).toBeCalled();
});
这篇关于使用Jest测试要调用的组件的onClose事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!