Testing React Components

Piero Divasto

M.Sc. in Business Informatics

Team Lead & Full-stack Developer @ Nisum

Lead de Facebook Developers Circle: Santiago

Test Frameworks

Test Frameworks

https://stateofjs.com/2017/testing/results

Test Frameworks

Helper Libraries

expect

Testing in React

Concepts

shallow

mount

render

used to render react components to static HTML and analyze the resulting HTML structure.

Full DOM rendering is ideal for use cases where you have components that may interact with DOM APIs, or may require the full lifecycle in order to fully test the component (i.e., componentDidMount etc.)

Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components.

Testing in React

Testing in React

Testing in React

const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.foo')).to.have.lengthOf(1);
expect(wrapper.find('.bar')).to.have.lengthOf(3);

// compound selector
expect(wrapper.find('div.some-class')).to.have.lengthOf(3);

// CSS id selector
expect(wrapper.find('#foo')).to.have.lengthOf(1);

// Constructor selector
import Foo from '../components/Foo';

const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Foo)).to.have.lengthOf(1);

// Component display name
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('Foo')).to.have.lengthOf(1);

// Object property selector
const wrapper = shallow(<MyComponent />);
expect(wrapper.find({ prop: 'value' })).to.have.lengthOf(1);

Testing in React

Testing in React

Snapshot testing

import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer
    .create(<Link page="http://www.facebook.com">Facebook</Link>)
    .toJSON();
  expect(tree).toMatchSnapshot();
});
exports[`renders correctly 1`] = `
<a
  className="normal"
  href="http://www.facebook.com"
  onMouseEnter={[Function]}
  onMouseLeave={[Function]}
>
  Facebook
</a>
`;

Testing in React

Snapshot testing

  • Bastante util para verificar que algo en el componente no haya cambiado de manera imprevista
  • Util si el componente no cambia frecuentemente
  • Util si el componente no es demasiado complejo
  • Util si realmente sabemos lo que queremos testear

Testing in React

DEMO

Testing React Components

By Piero Divasto

Testing React Components

  • 621