How To Write Tests To Check Your React Component Is Generating The Correct HTML

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}>

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

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top