Unit Tests with Enzyme

  • What is a unit test?
  • Enzyme and shallow rendering
  • jsdom and DOM rendering
  • Istanbul/nyc and test coverage

React makes unit testing extremely simple. Since every component is just a function and since most of our components are pure functions, it's easy to isolate just the pieces of the component you want to test without any side effects.

We are going to use Enzyme, which is a testing utility for React that clears up some of the awkward syntax of React's TestUtils.

One other advantage of testing React components is that you can test them without the need to render them to a DOM using something called shallow rendering. Shallow rendering is extremely performant and lets you run through your tests at blazing speed. This is because pulling up a DOM and rendering to it takes significant time, while simply calling a function is really fast.

What is a unit test?

A unit test is the smallest possible testing unit and should only test one thing. Unit tests are different than integration tests because integration tests are in place to make sure that our pieces work together. In short, unit tests make sure our pieces work by themselves, while integration tests make sure our pieces work together.

TODO need a graphic here showing the difference between a unit test and an integration test

An example of a unit tests would be taking a single React component and testing to make sure it does everything we want it to do. We might want that component to render a particular element to the DOM, or trigger a specific event. Now, the tricky part about unit tests is that we wouldn't actually care whether or not that event actually did anything--all we care about was that the event was triggered.

Functions (especially pure functions) are really easy to test because they will always give the same output given a certain input.

What to test?

We are going to test our Home component, which is just a wrapper. All we really need to tests is that a <div> renders.

For more complex components, you want to test to make sure that everything works the way it's supposed to given certain inputs. You don't want to rely on a database call or on anything outside the specific component that you are testing.

There is also the question of whether testing is worth the time for a particular component. When it comes to unit testing in React, it's really easy to go overboard. As a rule of thumb, if the CEO is going to give a live demo, you want to make sure you have really comprehensive tests for everything he would do in that demo.

It is also worth considering how you might later refactor a component, and how your tests would ensure that the component still operates the same way after the refactor. For example, in a Button component, you'd want to make sure that your component rendered its children and any other properties that are required for that component to render properly.

Setting up Enzyme

The first thing we need to do is install enzyme and all other dependencies we will need.

$ npm install --save-dev enzyme mocha expect react-addons-test-utils

Because we are using css-modules we will need to pass in an empty object as our style object and pass in a noop (short for "no operation" and pronounced "no op") for images and other non-JavaScript files (thanks to Ole Michelson for solving some of this issue). Create a .test-setup.js file and include the following to accomplish this goal:

We also need to add react-addons-test-utils because it is a dependency of Enzyme.

$ touch .test-setup.js
const noop = () => {}
const empty = () => ({})
require.extensions['.css'] = empty
require.extensions['.ico'] = noop
require.extensions['.png'] = noop
require.extensions['.jpg'] = noop
require.extensions['.svg'] = noop

We are also adding mocha so we can run our tests with Mocha using the command line mocha.

Writing a unit test

At this point, our Home component is pretty simple. All we are going to test is that it renders. Create a file called spec.js within our Home directory and add the following.

$ touch app/components/Home/spec.js
import React from "react"
import expect from "expect"
import { shallow } from "enzyme"
import { Home } from "./"
describe("<Home />", () => {
it("should render", () => {
const renderedComponent = shallow(<Home />)
expect(renderedComponent.is("div")).toEqual(true)
})
})

We're going to use expect, which is a simple assertion library that replaces assert, sinon, and chai for our purposes. Almost all of our assertions are going to come down to whether a certain statement is true or false. Generally speaking, if you're coming up with complex assertions you're probably over-complicating things. It also gives us access to spy, which we will go over later.

From enzyme we get shallow, which is a function that lets us shallow render our component without a DOM. The shallow API is really comprehensive and has good documentation. It would be worth your time to look over all the functions you have at your disposal here.

The next part is the describe block, where we (not surprisingly) describe the thing that we are testing. Within that describe block will be a series of it blocks that actually contain the tests we intend to run. it blocks usually follow the word "should", and that's a good way to think about what the code in the it block should do. In this case, it should render the children of our Home component.

The last line is where we make our assertion. If renderedComponent has been shallow rendered properly, then it will return a truthy value, which expect will pass. If the component is not rendered properly, then our test will not pass.

This is the only test you'll need for most of your components. Basically, we're just testing that the component was able to render without exploding.

If you find yourself testing a lot of logic within your component, you should really consider pulling that logic out into a separate part of your app (likely Redux, which we will go over later). Ideally, you want to keep your components as dumb as possible, meaning they just render content that is passed into them and don't execute any logic.

Running our tests

The last piece is actually running the tests. This is going to require a relatively complicated script in our package.json file.

But since we are not running our tests through webpack, we need to make sure we let Babel transpile our code. We can use babel-register to transpile our code before passing it on to mocha.

$ npm install --save-dev babel-register
...
"scripts": {
...
"test": "mocha --require babel-register --require .test-setup.js -R spec app/**/spec.js"
},
...

What we're doing here is telling mocha to run our tests, but first passing it through Babel (--require babel-register), then changing out our resolve.extensions with .test-setup.js so we don't have to use webpack, then recursively looking for all spec.js files within the app directory.

Now you can run it.

$ npm test

You should get an output like the following.

<Home />
should render
1 passing (32ms)

It's important to make your test fail in a predictable way so you know that you set your test up properly. Sometimes without knowing it, you might set up a test that passes no matter what you give it. We're not going to do that here for the sake of brevity, but you should make this practice a habit.

Full and static rendering

At a certain point, you'll need to run unit tests that require a DOM. If you want to check to make sure a certain action happened on componendDidMount, for example, you'll need to fully render the component so you have access to the lifecycle methods. To accomplish this, you will need Enzyme's Full Render API, which has a syntax almost identical to the shallow render API.

But before we can get this to work, we need a DOM running. The easiest and most efficient way to do this is with jsdom, which is a magical JavaScript implementation of the DOM that lets you run your tests extremely quickly since it's all done in JavaScript.

Setting up jsdom is a lot easier than you might expect. Enzyme provides an explanation of how to set it up, and we will walk through it here.

We can copy-paste the code from the documentation to the bottom of our existing .test-setup.js file.

const noop = () => {}
const empty = () => ({})
require.extensions['.css'] = empty
require.extensions['.ico'] = noop
require.extensions['.png'] = noop
require.extensions['.jpg'] = noop
require.extensions['.svg'] = noop
var jsdom = require('jsdom').jsdom
var exposedProperties = ['window', 'navigator', 'document']
global.document = jsdom('')
global.window = document.defaultView
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property)
global[property] = document.defaultView[property]
}
})
global.navigator = {
userAgent: 'node.js'
}

What this code is doing is taking our React code and putting it into the global namespace so it can be used by jsdom.

Then install jsdom.

$ npm install --save-dev jsdom

And that's all. Now you can run tests with mount and static, as well as shallow as you have before. The app is too simple to require tests of this sort, so we demonstrate the difference between these types of tests when it becomes necessary.

Just be sure you are running a more recent version of node. You must be using at least node 4. If you do not know what version of node you are using, run the following in your terminal.

$ node -v

If you find that your version of node is not at least 4.0, then update it with brew, nvm, or whatever method you prefer.

$ brew update
$ brew upgrade node

Istanbul and test coverage

Another feature that you see in nearly every production app is test coverage. Test coverage is an automated way to let you know how much of your app is covered by tests. If you have no tests, your test coverage is 0%. If you have tests for every function and for every line of code, your test coverage will be 100%. Most companies aim to have tests coverage of 80%-90%, depending on their risk tolerance.

Istanbul is the most popular tool for automated test coverage and it's used by just about every serious open source project. It's also surprisingly easy to set up. Start by installing it. For whatever reason, they decided to call the Babel-compatible command line tool for Istanbul nyc.

TODO this needs to exclude spec.js files from test coverage

$ npm install --save-dev nyc

Then we need to change our package.json scripts to run nyc over our existing tests so it can automatically detect how much of our code is covered by tests. We don't need to run this every time, so we will make it a separate command. This is going to look a little bit awkward.

...
"scripts": {
...
"cover": "nyc -x '**/*spec.js' -n 'app' -r text -r html -r lcov npm test",
...
}
...

While this command might look complicated, it's actually pretty reasonable. These commands tell nyc to exclude (-x) all of our spec.js files from our coverage report (because we don't a report on how well our tests are tested), include (-n) everything within the app directory, use the text, html, and lcov reporters (-r) and run npm test, defined within our scripts, to run the tests.

So now, if you run npm run cover, you will see your app with test coverage.

-----------|----------|----------|----------|----------|----------------|
File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
-----------|----------|----------|----------|----------|----------------|
All files | 90 | 100 | 0 | 90 | |
Home | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
Sidebar | 80 | 100 | 0 | 80 | |
index.js | 80 | 100 | 0 | 80 | 6 |
-----------|----------|----------|----------|----------|----------------|

You should also add the coverage directory to .gitignore so it doesn't get pushed to your repo.

node_modules
.DS_Store
npm-debug.log
dist
coverage
.nyc_output

If you're looking for something prettier than the terminal output, you can use your browser to open the index.html file within coverage/lcov-report. This will also give you hints as to where you should write additional tests to improve your test coverage.

Additional

We will write additional tests as we go along. Testing is an important part of ensuring the long-term stability of your app. Refactoring is inevitable, and if you have good tests, you can ensure that you don't break everything when you change around your components.

Previous: Snippets and AliasesNext: Basics of Elixir and Functional Programming