React Unit Testing Basics with Enzyme, Mocha, Chai, & Sinon

Photo by Timothy Dykes on Unsplash

Intro

You’ll probably want to include some unit tests in your build pipeline to avoid regressions. There are some popular options to help do this, jest being probably the most popular with mocha also high up there on the leaderboard. In this tutorial, we’ll cover some basics of mocha and how it integrates with chai, sinon, and enzyme.

  • mocha is a testing framework that helps us keep our unit tests organized.
  • chai is an assertion library that we use to make assertions about things.
  • sinon is a mocking library that lets us spy on, stub, and mock functions.

Context

Let’s say we’ve got two components: one parent — Marlin, and one child— Nemo.

Our First Unit Test

We’ll start with a simple unit test, modified from the one in the enzyme mocha integration example here. The point of this unit test is to make sure that our componentDidMount method gets called when we mount our component. Not a very useful test, but it’s a good example to start with:

Optimizations

Cool. That makes sense. There are some optimizations we can make, though. Notice that we used enzyme’s mount function. This will mount our Marlin component as well as any child components that Marlin calls within its render function.

Our Second Unit Test

Let’s add another unit test to make sure that our state gets updated properly. In this case, componentDidMount just sets the value of the state’s findingNemo variable to the value of the nemoIsLost property.

Common Pitfalls

Things get funky with arrow functions. In Javascript, arrow functions work a bit differently than regular functions (those created with the function keyword). Arrow functions are more lightweight than regular functions which means they’ve had to cut out some utility, notably the ‘this’ binding. This comes back to bite us when writing unit tests sometimes.

Marlin.prototype.foundNemo is not a function.

Outro

If you have any recommendations on how I can improve this or if anything is wrong, let me know.