How to test my React components

jose luis checa exposito
2 min readJan 25, 2020

--

…as I do

As one of my new year resolutions, writing my very first article was about to happen so here we are. Moving towards the goal of this article I wanted to tell you guys my idea based on my developer/personal experience about unit testing my react components.

As we know one of the most important testing libraries to React for the last years has been Enzyme which I have been used for a while. But recently I have started using react-testing-library which in my humble opinion, and after many researches and arguments with my coworkers, is what testing in React is moving to.

Enzyme is exposing an amazing API which allows you to mock children and have access to implementation details so the way that I was unit testing my React components.

  • Stateful/Containers: Use shallow render and unit testing my methods checking the state of my components if changes. Also, test the markup using snapshot or testing by finding elements. In this way, I was trying to isolate my module logic.
  • Stateless/Presentational: Unit testing the callback functions passed down by the parent component and markup.

With react testing library the concept of testing is different as the library is rendering the component and allow you to interact with it as a user would do. I have realised the way I was unit testing my component with enzyme is could be right and well tested but in real life, my app as a whole, could not work as expected.

Therefore I have decided to move forward to more integration testing. What I mean with this integration test is, now you will have to render your container with its children, query the elements within the DOM, interact with them and check the changes in the DOM instead of the state itself. Also for stateless component, you will be able to check that the callback has been called with the expected data.

Maybe you guys can comment that I could do more or less the same with mount a component in Enzyme which I agree that could be more integration testing but the idea of the using this react testing library is the concept of stop testing the implementation of my components and testing the app as a whole.

Thanks for reading it and I hope you guys like it.

--

--

jose luis checa exposito

Coming from a tech-hub like London provided me the necessity and the capability of keep myself up to date. Love the interaction with other and sharing knowledge