Code Snippets To Help You Unit Test Forms Written In React

In this tutorial, I share several useful code examples that will help you test your components that incorporate a standard HTML form, written in React.js. 

When it comes to building and testing a website, you should aim to have higher test coverage around the complex dynamic parts - like a form - compared to your simple static pages like a website's cookie policy page.  A lot of people new to programming don't bother writing unit test.  The main reason being, it's too complicated, or, it's a waste of time. 

The code snippets in this post, should give you a quick copy-and-paste reference on how to test your forms, sound good?  

My React Form

First, let's assume we have this form:

export default class MyForm extends PureComponent {
    handleSubmit = event => {
        event.preventDefault();
    };

    render() {
        const { children, handleSubmit } = this.props

        return (
            <form onSubmit={handleSubmit || this.handleSubmit} >
                <label>email</label>
                <input type="email" name="email" />
                <select className="select">
  {children}
</select>
                <button type="submit" />
                {children}
            </form>
        )
    }
}

How To Test Your React Form Has Been Submitted Correctly

In this test, we will simulate the forms submit button being clicked and then testing that the onSubmit() event is called as expected:

const handleSubmit = jest.fn().mockImplementation((cb) => () => cb({ test: 'test' }));
const wrapper = shallow(<MyForm form="test" handleSubmit={handleSubmit}   />);
wrapper.find('form').simulate('submit');
expect(handleSubmit).toBeCalledTimes(1);

Instead of using .simulate('submit'), you could also called using .simulate('click'), like so:

const handleSubmit = const handleSubmit = jest.fn().mockImplementation((cb) => () => cb({ test: 'test' }));
const wrapper = shallow(<MyForm form="test" handleSubmit={handleSubmit}   />);
wrapper.find('button').simulate('click');
expect(handleSubmit).toHaveBeenCalled();

How To Test Adding Text Into A Textbox

Sometime you will need to test a user adding some text to a textbox. You can do this using the .simulate('change' event, like so:

const handleSubmit = jest.fn().mockImplementation((cb) => () => cb({ test: 'test' }));
const wrapper = shallow(<MyForm form="test" handleSubmit={handleSubmit}   />);
const input = wrapper.find('input');
input.simulate('change', { target: { value: 'some text' } });

// test some feature

How To Test Adding A Checkbox

You could simulate a user selecting/unselecting a checkbox, with something like this:

wrapper.find('.selector').simulate('change', { target: { checked: true } });

How To Test Animations On Your Forms

If you have any animations on your form, you can simulate and test what happens, using the following snippet:

const handleSubmit = jest.fn().mockImplementation((cb) => () => cb({ test: 'test' }));
const wrapper = shallow(<MyForm form="test" handleSubmit={handleSubmit}   />);
wrapper.simulate('animationEnd', { animationName: 'fadeOut' });

//  test some feature

How To Test A Feature After it Has Been Loaded

If you have any AJAX requests, or, lazy loading in your form, you can simulate a page load event, using .simulate('load'):

const wrapper = shallow(<MyForm form="test"/>);
wrapper.simulate('load');
expect(wrapper).toMatchSnapshot();

How To Test A Dropdown List Has Loaded Correctly

If you have a select component within your form, you can test it in several ways, using events like simulate('blur') and .simulate('focus'):

const handleSubmit = 
const wrapper = shallow(<MyForm form="test"    />);
wrapper.find('select').simulate('blur');        

Or...

const wrapper = shallow(<MyForm form="test"    />);
wrapper.find('select').simulate('focus');   

How To Test A Dropdown Value Has Changed Correctly

If you need to test what happens in your component after a user has changed the value of a dropdown - like the textbox input - you can use .simulate('change')

const wrapper = shallow(<MyForm form="test"    />);
wrapper.find('select').simulate('change', { target: { name: 'day', value: '05' } });

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