I have a component that's structured like so:
// inside render()
return <div style={styles.root} onMouseLeave={this.mouseLeave}>
<Button
label={label}
onClick={this.buttonClick}
{...other}
/>
{this.state.clickedOnce ? warning : null}
</div>
I understand that with snapshot testing, I could test the props exposed by my component like this:
tree.props.onMouseLeave();
tree = component.toJSON();
expect(tree).toMatchSnapshot();
But what if I wanted to trigger an onClick on the Button? I tried this in my test:
tree.children[0].props.onClick();
tree = component.toJSON();
expect(tree).toMatchSnapshot();
And it seems to work fine. Is there a better way? I also had to modify my onClick handler:
buttonClick({ nativeEvent: event }) {
if (!this.state.clickedOnce) {
this.setState({ clickedOnce: true });
} else {
if (!this.props.catastrophic || event.shiftKey) {
this.setState({ clickedOnce: false });
this.props.onConfirm && this.props.onConfirm();
}
}
}
Jest didn't like trying to access event.nativeEvent, which I think I had in place because I was having some issues accessing event.shiftKey otherwise. But I switched the function signature to just be buttonClick(event) and it seems to work fine.
I have a component that's structured like so:
I understand that with snapshot testing, I could test the props exposed by my component like this:
But what if I wanted to trigger an
onClickon theButton? I tried this in my test:And it seems to work fine. Is there a better way? I also had to modify my
onClickhandler:Jest didn't like trying to access
event.nativeEvent, which I think I had in place because I was having some issues accessingevent.shiftKeyotherwise. But I switched the function signature to just bebuttonClick(event)and it seems to work fine.