Testing Higher-Order Components with Mock Classes on React 16

on Testing, Javascript,

With unit tests for ReactJs higher-order components, usually a mock component is wrapped for testing.

A setup function like beforeEach, is a good place to put the mock React component.

 1// __tests__/hoc.js
 2import React, { Component } from 'react';
 3import { shallow } from 'enzyme';
 4import toJson from 'enzyme-to-json';
 5import withHoc from '../hoc';
 6
 7describe('higher-order component', () => {
 8  let MockComponent, WrapperComponent;
 9
10  beforeEach(() => {
11    MockComponent =  React.createClass({
12      render: () => {
13        return (<div>Component</div>);
14      }
15    });
16
17    WrapperComponent = withHoc(MockComponent);
18  });
19
20  test('withHoc should render without crashing', () => {
21    const wrapper = shallow(<WrapperComponent/>);
22    expect(toJson(wrapper)).toMatchSnapshot();
23  });
24});

Running the test above will get you the error message: TypeError: _react2.default.createClass is not a function

Since moving to React 16, React.createClass is removed. You may have noticed the warning in React 15 if you had used it then.

React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you’re not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.

The solution is just to rewrite the component as a Class:

 1describe('higher-order component', () => {
 2  let WrapperComponent;
 3
 4  beforeEach(() => {
 5    class MockComponent extends React.Component {
 6      render() {
 7        return (<div>Component</div>);
 8      }
 9    };
10
11    WrapperComponent = withHoc(MockComponent);
12  });
13
14  test('withHoc should render without crashing', () => {
15    const wrapper = shallow(<WrapperComponent/>);
16    expect(toJson(wrapper)).toMatchSnapshot();
17  });
18});