Easily testing React components with react-test-tree

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!