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:

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() e`vent is called as expected:

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

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:

How To Test Adding A Checkbox

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

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:

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'):

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'):


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')