ReactJS / Redux Unit Testing

Updated 8 months ago

This document uses GitBook plugins to add formatting beyond standard GitBook. Not all plugins produce consistent format across document types (e.g.: PDF); best viewed online.

This document is ~25% complete…

Quote::Legacy-code is simply code without tests.

With tests, we can change the behavior of our code quickly and verifiably. Without them, we really don’t know if our code is getting better or worse. ~ Michael Feathers

Everybody has an opinion about what the UI will look like. Their opinions will be expressed up until and after a final ship. Though UI can be the most challenging part of the software stack to test, it is the part that can benefit the most from UT's simply due to the expectation of change during what can be the most pressure-packed time frames of a product's schedule. I am not only thinking of The End, but also during acceptance testing at sprint's end.

That said, up until ReactJS, the UT return-on-investment of the UI layer has been staggeringly low, if not negative for a host of reasons not limited to:

  • UI designs that may follow standard, easy to read, expressive, ... implementation patterns yet challenge test isolation.
  • UI testing environments typically depends on a more diverse set of add-ons to assist with unit isolation (mocking, stubing, spying). IOWs: a bumped-up learning curve devoted to tooling.

ReactJS Unit Testing Intro

ReactJS's one-way data binding with a focus on pure functions to render components substantially lowers investment. UT'ing a pure function, a function that yields the same result for the same data input, is far easier than functions that have side affects (that change data). A pure function is not affected by the surrounding state-of-system under test.

The Javascript UT ecosystem is rich with support projects geared toward unit isolation and test running. Add ReactsJS pure functional design with a handful of ReactJS-specific support packages to isolate Components and state stores, and 'Voila!'. UT'ing becames not only possible, but down-right easy.

I will present an opinionated design that is inherently testaable for both the state (Redux) and presentation areas that makes up a simple ReactJS app within a Webpack build environment. I will also touch on creating a fast feedback test running; so fast that a developer could practice Test Driven Development (TDD) should they desire.

The gkedge\/ReactJS-Redux-Unit-Testing GitHub repository provides focused examples of each technique shared in this tutorial.

Before I get into all that, let me touch on a new-for-JS (trending?) practice that assists developers to avoid bugs ahead of even testing...