Testing Custom Events With Enzyme (React)
In this blog we will learn how to test custom events in react. We have a togglable component which can be used on a page to toggle data or a view.
Source Code for the TogglableComponent and the component where it is used.
Now we want to test the functionality in the component where the TogglableComponent is used. In this case, Home Component.
In Enzyme simulate function is used to trigger the events on the wrapper.
For eg. here we simulate click on a <button/> and checking if the state of TogglableComponent is disabled.
Now we want to test the functionality in Home Component if the toggling work in the way it is intended to
How to Test Custom Events
Option 1: By calling the internal method or an event which is attached to TogglableComponent and also which is passed as props to it.
Disadvantages with this option are we are not really testing the functionality. We are only testing the internals of the component.
So the binding of the function with the element might go untested. Also, it becomes to difficult refactor as implementation is coupled with the testing.
Option 2: Can we use Enzyme to trigger custom events? Yes we can
To be able to trigger the toggle custom event, the prop name should start with “on”. In above case the custom event is onToggle and we simulate toggle in tests. Similarly “onJump”, “onAdd” custom events can be tested.
Thanks to Monika M for her help in writing this blog.
This stackoverflow question was motivation behind writing this blog
The issue for testing custom events for shallow rendered children in enzyme is still opened on https://github.com/airbnb/enzyme/issues/147