Unit testable components pt.1: Overview

Bad tests are worse than no tests

This code should be changed or refactored, but that would mean I have to update my tests...

Testing UI behavior is really hard, and you can get lulled into writing sloppy tests. Sloppy tests are unmaintainable and encourage "behavior locking". It's a problem that only grows as time goes on.

Testing React components is hard

Frontend testing requires, in one form or another, a mocked DOM, which is a beast in its own rite. Your tests can't be run like a basic function, because the true environment is the browser. Which is what enzyme was created for. It's a mandatory supplement to jest for component testing.

Component design matters a lot more than you think

Well designed components are easy to test

Spaghetti is easy to right, but hard to test and maintain. Large components also hurt performance, for reasons that can be dove into on another day. Here are the qualities that I value when I design components.

  • Small components that represent a singular idea
  • Few or no props passed in from parent (flux implementation needed)
  • Minimal business logic

When you do things the right way, everything just "falls right into place"

These principles that I value make code clean, maintainable, and implies separation of concerns (which vanilla React does a bad job of). Deep dependencies between UI elements and their resulting behavior inside a component is the pain point when it comes to testing. It is advantageous to minimize it.

Redux gives us an ecosystem to create separation of concerns

Redux is its own data flow ecosystem. Its algorithmic operations have nothing to do with the DOM. The only job of flux is to feed data to components, making it the perfect place to abstract out complex behavior.

Testing advantages of abstracting out business logic

  • Very few mocked functions (one or two, at most)
  • No spies
  • No value assertions of actions or api calls (except for local state and render logic)
  • Only render logic needs to be asserted

Starting to sound pretty nice, right? Well, sit tight. I'll get to it in pt.2

Comments

Popular posts from this blog

Contrasting var and ES6s new declarations: let and const

Modularity vs. Abstraction. Which is More Important?

Unit testable components pt.3: Testing components