I am building an app with React. I am hiding a file input element (<input type="file"/>
) "behind" a react-bootstrap Button
to be able to control styling. So, when the button is clicked I turn around and fire a synthetic click event on the text input element, as shown below.
class OpenFileButton extends React.Component {
...
clickHandler() {
this.refs['input'].click();
}
render() {
return (
<ButtonGroup>
<div>
<input type="file" onChange={this.props.someCallback}
ref="input" style={{display: 'none'}}/>
<Button onClick={this.clickHandler}>Open File</Button>
</div>
</ButtonGroup>
);
}
}
I want to be able to test this with Jest/Enzyme. However, while I can simulate a click event on the button, I haven't figured out how to detect a synthetic click event on the file input element.
I have tried using Jest/Enzyme to mock the click method on the input element.
const component = mount(<OpenFileButton/>);
const fileInput = component.find('input');
const button = component.find('Button');
fileInput.click = jest.fn();
button.simulate('click');
expect(fileInput.click).toHaveBeenCalled();
However, mocking the click
method this way does not work. I also can't add an onClick
attribute, i.e. fileInput.props().onClick = jest.fn()
does not work.
This question is about detecting synthetic click events in the code itself, not in the test code, and so is not relevant.
So, how can I detect a (synthetic) click event on a DOM element using Jest/Enzyme?