Manually testing forms to ensure they work as we expect is very time consuming and laborious, so having a unit test to automate this process is a godsend.

A simple contact form (found on nearly every website) is a good example of a form that we can generate a unit test for.

To get started I mocked up a basic form with name, email, phone and message field. I then created the route to display the form and added a simple ajax request to submit it. I then added a second route to validate the post data and return a JSON response that can be used to display the success/error message.

Now we have something to test, we can get started with Laravel Dusk.

The official documentation here contains an excellent introduction to getting started.

In this particular case, I wanted to ensure that the form is correctly submitted and passes the validation. To do this I created a new test called "it_passes_validation" and filled out all the required fields. Finally I instructed Dusk to submit the form and look for the correct response message. The test can be seen below.

There are many ways to check the result after it has been submitted, the easiest in this case was to check the page for the success message, but I could have looked for other signs. Such as, seeing if we were redirected to success page or an input had been updated with a success value. It really depends on the way the form reacts to submissions and every website seems to handle it differently.

If the form were to redirect to a success page, we could modify the test to assert the 'path' of the page, like so:

Please review the key information you’re about to submit. Don’t worry if things change before a meeting, it’s just to give us some insight to get started.My name is . I’d like to start a project, with a budget of £. I’m hoping to have this completed .My telephone is and my email is .