Testing React components using enzyme and jest mock/spyOn
When we are working on the react application, it’s common we end up with a lot of small and concise methods. These methods generally contain some logic which is being used in some part of the component.
While working on some incremental changes or any bug fix, a developer could end up breaking the existing logic and hence the overall functionality. So it becomes super important to test those logics and all permutation-combinations there only instead of having a happy path at the end of the development.
Now let’s visit how we can easily test such logics with minimal code possible.
I have created two components, Parent
and Item
in which parent displays a list of text and delegates the list items to Item
component. Further Item
component contains some internal methods which contain some logic and dependency on each other.
In this blog, we will concentrate mostly on
how to test
and leave the discussion ofwhat to test
for some another day.
Now, we have a parent and child(item) component with some mutual dependency. There is also a callback method being passed from parent to child which will be invoked on click event.
Sometimes, we end up not testing such scenarios but if not tested, one could end up in broken functionality in the near future.
For parent component, I am doing only some basic testing like :
- if content exists
- if the correct text is being displayed
- if the correct number of list items are rendered.
Please have a look at parent.test.jsx file
On the other side, testing of item component is a little tricky. Here I would like to test :
- callback method is being called correctly on click event
- if one method inside component is calling other correctly
- invoking one method correctly sets the component state
As of now, this should be enough to kick start you with jest, enzyme, mocks and spy methods. Further, I will also be adding :
- how to mock implementation of certain methods
- how to mock external libraries and dependencies
- how to test async code and API calls.
Stay tuned for further testing techniques.