Easily testing React components with react-test-tree

James Hollingworth
May 20, 2015 · 2 min read

While I love React, testing React components leaves a lot to be desired. The TestUtils are useful but don’t have a particularly intuitive API and lead to verbose tests, e.g.

We’ve been working on a library at Qubit (We’re hiring) called react-test-tree which removes a lot of the pain with testing React components.

It does this by creating an object that represents the given component with an API designed for testing. If you want to make assertions on an element in your component, all you need to is add a ref and it will be exposed for testing. Rather than having to simulate events, we give you simple functions (e.g. .click()) to call instead.

So what about if I’ve got a collection of elements? We introduce a new attribute, refCollection, which you must add to the parent element. Any children will be available as an array on the test tree.

Often when you’re writing your tests you want to prevent certain parts of the component from being rendered e.g. if that part isn’t relevant to the test. React introduced shallow rendering in v0.13 however we’ve found its rather limited, not allowing the fine grained control we desired. react-test-tree provides a different approach, allowing you to stub refs:

Another thing we often found ourselves doing was passing values down through the context (e.g. if you want to mock react-router’s router) . This is again trivial with react-test-tree, all you need to do is pass your context object in via the childContext option.

We’ve found react-test-tree is a massive help in testing react components. Theres always room for improvement so would love to hear what you think!

Qubit Engineering

Qubit.com’s engineering blog

James Hollingworth

Written by

Engineer @ Qubit

Qubit Engineering

Qubit.com’s engineering blog

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade