I had a lot of problems when testing addEventListener, and I got the following conclusion.
You can create an event listener using pure javascript, jquery, but when running tests with Jest I always had a problem.
Rendering ReactTestUtils does not work directly with the document, and when we do:
For example, our events were added to a document, when rendering with ReactTestUtils, it creates a div and displays it in a div. Thus, I could not get Simulate to invoke the call.
My first solution was to use jquery to create a listener and verify that I did the rendering manually by adding a div to document.body and triggering events using the javascript dispatcher. But I thought the code was dirty, not the best way to work.
I made a code example, adding an event and testing it with Jest, we also get test training to get the whole created listener.
The code can be found here: https://github.com/LVCarnevalli/create-react-app/tree/master/src/components/datepicker
component:
componentDidMount() { ReactDOM.findDOMNode(this.datePicker.refs.input).addEventListener("change", (event) => { const value = event.target.value; this.handleChange(Moment(value).toISOString(), value); }); }
Test:
it('change empty value date picker', () => { const app = ReactTestUtils.renderIntoDocument(<Datepicker />); const datePicker = ReactDOM.findDOMNode(app.datePicker.refs.input); const value = ""; const event = new Event("change"); datePicker.value = value; datePicker.dispatchEvent(event); expect(app.state.formattedValue).toEqual(value); });
References:
window.addEventListener is not triggered by simulated events: https://github.com/airbnb/enzyme/issues/426
Creating and triggering events: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
Lucas carnevalli
source share