The Dangers of Shallow Rendering

Three reasons why you should avoid shallow rendering when writing JavaScript component tests

Sign reading “danger no entry”.
Photo by Issy Bailey on Unsplash

TLDR

Rather than making you scroll all the way to the end to see my list of reasons, they are listed succinctly in the following list. If you don’t like what you see, you won’t be forced to read any more. 🙂

  1. Shallow rendering decreases confidence.
  2. Shallow rendering complicates refactoring.

Shallow Rendering Creates Additional Failure Points

A blue and white plate shattered on a concrete floor.
A blue and white plate shattered on a concrete floor.
Photo by chuttersnap on Unsplash

Shallow Rendering Decreases Confidence

A very long bridge over a valley between two mountains.
A very long bridge over a valley between two mountains.
Photo by Jonathan Klok on Unsplash

Shallow Rendering Complicates Refactoring

Orange colored neon sign with the word “change”.
Orange colored neon sign with the word “change”.
Photo by Ross Findon on Unsplash

A Better Way

If you are convinced that shallow rendering is not a good testing practice, the next big question is what to do instead? While there are many ways to answer this question, my current thoughts are best described with the following recommendations:

  1. Think less about props/state and more about user behavior. Rather than directly interacting with your components props, instead try rendering additional DOM elements which you can interact with which in turn affect your component. This is more similar to a real application where user interaction affects your component.
  2. Never under any circumstance use APIs which allow you to directly affect component state (e.g. Enzyme’s setState method). This does not accurately reflect user behavior. Directly modifying props is also not ideal, but it is less problematic than directly modifying state.
  3. Try out React Testing Library which does not support shallow rendering and has an API which prevents many common testing patterns which test implementation detail. Although not required to write good tests, I have found it very helpful in increasing the quality of my tests and the confidence they provide.

JavaScript Engineer @Widen using JavaScript, TypeScript, and React.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store