In this tutorial, I will share some code with you that checks that some content exists within a div with a specific class name. The main reason I've written this tutorial is because I've wasted the last two hours trying to write a test and completely forgot the syntax :)

The Code

For the readers who just want to get straight to the code, then here you go:

import React from 'react';
import { shallow, mount } from 'enzyme';

describe('Example Test component', () => {

    it('should render correctly', () => {
        const testText = 'ddddddddd';
        const testClassName = "myClass";
        const wrapper = shallow(
            <div className={testClassName}>
                {testText}
            </div>
        );
        expect(wrapper.find(`.${testClassName}`).html()).toContain(testText);
    });
});

Some of the useful things to note about the above:

  • When you want to test a react component end HTML use the .html() method on the returned mount/shallow component.  If you do not do this, you'll be trying to run your test against the react JSON object that defines the property.
  • Shallow Vs Mount: Mount takes longer to run than shallow.  Use mount() when you need to test the component, its events and child components. Shallow doesn’t descend down to sub-components and can be used for quick UI tests
  • use find() to search for elements in your HTML.  Normal CSS selectors work in here.

Tips When Writing Tests In React

The main coding offences that will make your React components that are difficult to test. are:

  • Massive, monolithic objects being passed in.  This results in mocking more code than you need to.  When you pass a prop into a component, double think if you can simplify the amount of data being passed in.  
  • Not breaking components down into smaller HOC.  You can tell this is happening as your unit test end up being longer than 20 lines of code.  In these instances, try and make your component smaller somehow.
  • Lastly, I would recommend you bookmark these two shortcut pages, which can be very helpful: JestEnzyme