React Unit Testing with Tape

Matthias Gattermeier Blocked Unblock Follow Following Dec 17, 2015

Update. June, 2016: If you are working on a bigger project you might find Tape not quite up for the job, take a look at React Unit Testing with Enzyme, Lab and Code

This is a short intro into testing React applications using Tape. If you were wondering why you should be using Tape over Mocha/Chai/etc, read Eric Elliott’s excellent Medium article on the topic.

For this tutorial we’ll be using a technique known as shallow rendering for React components. It provides a convenient way to render a React element only one level deep, which means that the component’s children will not trigger their render methods. Great for unit testing.

To make our lives easier we extend tape with Algolia’s tape-jsx-equals which utilizes react-element-to-jsx-string to compare the rendered output of a component against the expected value. This is great to test the whole (shallow) rendered output of a component.

For more detailed unit tests we use react-unit, which allows us to easily query component details or run tests against a prop value of a specific element inside a component.

We use babel-tape-runner to make full use of ES2015 and pipe the test results through faucet for better console output.

Ok, now let’s get into the weeds. Here our sample component, a simple Share button, with a label, and not much more.

An this is how our test file should look like:

Note that we are not using t.plan(), but t.end() as jsxEquals runs several tests depending on the rendered output, which makes it unnecessary inconvenient to predict and count. (Or I’m just lazy :)

Add your test npm command to your package.json file:

"test": "babel-tape-runner tests/**/*.js | faucet"

Install the dependencies we need:

npm i --save-dev tape babel-tape-runner extend-tape tape-jsx-equals react-addons-test-utils react-unit react babel-core faucet babel-preset-es2015 babel-preset-react babel-preset-stage-0

You should be able to run your test:

npm test

And should see output like this:

For your convenience you can just grab the repo here.