Testing React applications

React test utils

var ReactTestUtils = require('react-addons-test-utils');

Shallow Rendering

  • Does not require a DOM
  • Does not instantiate or render child components
  • Allows to assert facts about what a component's render method returns "one level deep"
 

Shallow Rendering

// Create a shallowRenderer instance
const shallowRenderer = ReactTestUtils.createRenderer()

// Create an instance of the component to be tested
const myComponent = React.createElement(MyComponent)

// Render the component with the shallow renderer
shallowRenderer.render(myComponent)

// Get the output of the render method
const result = shallowRenderer.getRenderOutput()

// Create assertions for that result
expect(result).to.be.eql('whatever')

Simulate*

// <button ref="button">...</button>
var node** = this.refs.button;
ReactTestUtils.Simulate.click(node);

*Simulate needs a DOM to work

** node must be a React Component instance and not a React Element

Demo

Enzyme

Enzyme features

  • AirBnB javascript assertion library for React.JS
  • Mimics jQuery's DOM manipulation API
  • Bullet Three

Shallow Render

import React from 'react'
import { shallow } from 'enzyme'

import MyComponent from './MyComponent'
import Foo from './Foo'

describe('<MyComponent />', () => {
  it('renders three <Foo /> components', () => {
    const wrapper = shallow(<MyComponent />)
    expect(wrapper.find(Foo)).to.have.length(3)
  })
})

find()

// Finds by React component
expect(wrapper.find(MyReactComponent)).to.exist

// Finds by DOM element
expect(wrapper.find('h1').hasClass('centered')).to.equal(true)

// Finds by class name
expect(wrapper.find('.my-button').hasClass('disabled')).to.equal(true)

Simulate

it('simulates click events', () => {
  const onButtonClick = sinon.spy();
  const wrapper = shallow(
    <Foo onButtonClick={onButtonClick} />
  );
  wrapper.find('button').simulate('click');
  expect(onButtonClick).to.have.property('callCount', 1);
});

Testing Redux

ToDo

References

Testing React.JS Applications

By Daniel de la Cruz Calvo

Testing React.JS Applications

Approaches and tooling for testing React.JS applications

  • 861