Unit testing React components with Jest

Jest is a unit test framework for testing React apps. The Getting Started guide is pretty much all you need to get started. If you’ve created your project using create-react-app then you’re already setup, just run ‘npm test’ and a runner will test up that repeatedly runs your tests as you make code or test changes.

create-react-app also creates a sample test for the sample App.js component. This is a good starting point to follow for other tests:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App/>, div);
});

To test the results of rendering a component, the enzyme library allows you to easily capture the output from a render, and then query the results. For example:

import React from 'react';
import ReactDOM from 'react-dom';
import {shallow, mount} from 'enzyme';
import Calculator from '../Components/CalculatorComponent';
it('renders with result 3', () => {
    const result = mount(<Calculator value1="1" value2="2" />);
    result.find('button').simulate('click');
    const buttonResult = result.find("#result").first();
    expect(buttonResult.text()).toEqual("3");
});

The CalculatorComponent I’m testing here is the one from my previous React post.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.