React Testing Tricks

This post is a grab-bag of a few techniques I’ve found very useful for testing React components.

The toolkit is Karma, Mocha, Chai and react-test-tree.


Fast feedback loops are essential, and Karma is the best I’ve found. I like the clear-screen and nyan reporters.


Always test the happy path

Every component must test it can render without blowing up.


Syntactic sugar over ReactTestUtils. The biggest win here IMO is the use of refs to give a clean PageObject interface.

Instead of obscure methods which know too much about the internal HTML, just use the exposed refs –

To click the close button, invoke

More detail on this great tool is here. I’m never using ReactTestUtils again.

Factory Method

A thorough test will involve many instantiations of a component with minor variations. Instead of copy-pasting creation code, make a factory function, such as:

  function htmlModal(kids, extraProps) {
    return testTree(<CModal
      closeCallback={() => {}}
      title="Modal title"

Notice the {...extraProps} bit above? JSX spread attributes allow passing in arbitrary extra attributes to override the defaults.

Use ES6 enhanced object literals to pass in the properties: const page = htmlModal(<div/>, {closeCallback});


Sinon is a clean way to test callbacks (and provide mock HTTP servers):

  it("Should close the modal", () => {
    const closeCallback = sinon.spy();
    const page = htmlModal(<div/>, {closeCallback});;


Put ‘em together

And you get fast, readable concise tests!