Skip to content Skip to sidebar Skip to footer

Detect Synthetic Click In React During Testing With Jest/enzyme

I am building an app with React. I am hiding a file input element () 'behind' a react-bootstrap Button to be able to control styling. So, when the button

Solution 1:

<input /> or this.refs.input is an instance of HTMLInputElement.

Then you can test if HTMLInputElement.prototype.click is called .

Using you will have :

import sinon from'sinon';
import {mount} from'enzyme';

const clickInputSpy = sinon.spy(HTMLInputElement.prototype, 'click')
const component = mount(<OpenFileButton/>);

const button    = component.find('Button');

button.simulate('click');
expect(clickInputSpy.called).toBeTruthy();
clickInputSpy.restore();

const clickInputSpy = sinon.spy(HTMLInputElement.prototype, 'click');


console.log(
 'Is <input /> clicked ? ', clickInputSpy.called 
);
document.querySelector('input').click();


console.log(
 'Is <input /> clicked ? ', clickInputSpy.called 
);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.15.4/sinon.min.js"></script><input />

Solution 2:

The solution here involves spying on the click method of the particular file input element that I'm interested in. I can thus check to see if this file-input-element-click-spy was called after a click is simulated on the button element, as follows:

const openFileButtonWrapper = mount(<OpenFileButton/>);
const buttonWrapper = openFileButtonWrapper.find(Button);
const fileInputWrapper = openFileButtonWrapper.find('input [type="file"]');
const fileInput = fileInputWrapper.get(0);
const clickInputSpy = spyOn(fileInput, 'click');
buttonWrapper.simulate('click');
expect(clickInputSpy).toHaveBeenCalled();

The answer by @AbdennourTOUMI used Sinon's spy method which reminded me that Jest uses some Jasmine functionality, including its spyOn method, that isn't obvious from the Jest documentation. So, even though that other answer ended up spying on _all_ input elements, which is not ideal, it did send me in the right direction, so thank you, Adbennour.

Post a Comment for "Detect Synthetic Click In React During Testing With Jest/enzyme"