In this tutorial, I share several useful code examples that will help you test web forms that have been written in ReactJS. 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 common excuses for not origin test it's usually it's too complicated, I don't have enough time, or, testing isn't a valuable investment of effort. The code snippets in this post, should give you a quick copy-and-paste reference on how to unit test your forms, so the entry-level to get started is simpler. Sound good?

My React Form

First, let us 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. The test will make sure the onSubmit() event is called as expected:

The test above will make sure that the correct function is called when the submit button is clicked. An alternative way of testing this is to swap .simulate('submit') to .simulate('click'), like so:

How To Test Adding Text Into A Textbox

Sometimes, you will need to test a user has added some text to a textbox correctly. 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 selected 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 a textbox input - you can use .simulate('change'). The test to do this would look like this:

As you can see, testing forms does not have to be hard. There are lots of easy ways to mock the forms functions. I am hoping these snippets will make your life easier and convince you to start writing tests! Happy Coding 🤘