JONDJONES.COM
  • About
  • CMS
  • Clean C#
  • Javascript
  • Resources
  • Ask Jon
  • Hire Me
  • Contact
Follow Me
  • ;

what are you looking for?

JONDJONES.COM
  • About
    About Me
    • Who Is Jon D Jones?
    • Things I Use
    • My Projects
    How You Can Help
    • How You Can Support This Site
    • Submit A Guest Post
  • CMS
    CMS Tutorials
    • Umbraco
    • Sitecore
    • Episerver
    Resources
    • Episerver: The Missing Manual
    • #ILoveEpiserver
    • #ILoveUmbraco
  • Clean C#
    • TDD
    • Clean Code
    • Devops
    • Faster Page Load Times
    • Developer Tool Tutorials
  • Javascript
    Tutorials
    • Javascript
    • React
    • CSS
    Resources
    • #ILoveJavascript
    • Dev Tools List
    • #ILoveReact
  • Resources
    Free Guides
    • Shit My Websites Down...
    • #ILoveJavascript
    • #ILoveReact
    • #ILoveTechnicalInterviews
    • Land Your First Contract
    Books
    • Episerver Missing Manual
  • Ask Jon
  • Hire Me
    My Services
    • Umbraco Freelancer
    • Episerver Freelancer
    • Sitecore Freelancer
    • Javascript Freelancer
    My Company & Experience
    • Digital Prompt
    • My Portfolio
    • LinkedIn Profile
    • Stackoverflow CV
  • Contact

Code Snippets To Help You Unit Test Forms Written In React

  • Homepage
  • Frontend
  • React
  • Testing React Components
  • 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 tests.  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 is 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

Sometimes, 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' } });
Code Snippets To Help You Unit Test Forms Written In React
Code Snippets To Help You Unit Test Forms Written In React
How To Write Tests To Check Your React Component Is Generating The Correct HTML
How To Write Tests To Check Your React Component Is Generating The Correct HTML
Running A Single Test Using Jest
Running A Single Test Using Jest
Unit Testing React Redux Connected Components
Unit Testing React Redux Connected Components
Useful Code Snippets To Help You Test Your React Components
Useful Code Snippets To Help You Test Your React Components
Using Yarn To Bump Your React.js Packages
Using Yarn To Bump Your React.js Packages
FOUND THIS TUTORIAL USEFUL? PLEASE CONSIDER DONATING
FREE BOOK
Shit My Websites Down
DOWNLOAD NOW

Subscribe

Join us today and get instant access to FREE books

YOU ARE A LEGEND!

You just made.. THE LIST!

SUPPORT THIS SITE
CLICK AN AD!

WELCOME

Hi, I'm Jon, I write articles about creating and optimizing websites to help your business meet its goals. I am a technical architect and technology fanatic by profession. You can find out more about me by joining my newsletter.

Latest Posts
  • Umbraco V8 Fails To Load On Remote Server
  • How To Enable Optional Chaining Within Your Javascript Project
  • How To Call An API Within A React.js App
  • Quick And Dirty Guide To Deploying Your React App

© Jon D Jones