How to test a Laravel JSON controller
My side-project Cronhub is a Vuex application powered by Laravel. I use Laravel as an api backend as well as to handle the authentication part of Cronhub. Most of my routes are JSON controllers that make CRUD operations on my models. As any other application I have a resource called User
.
In this short tutorial I’ll show how you can approach testing a simple Laravel API controller. My example is based on the User model. I have a controller called SettingsController
which is responsible of updating the user settings data from the frontend.
Here is the simple view of the UI.
When the “Save” button is pressed it makes a call to settings/user
route defined in api.php
route file.
Route::put('/settings/user', 'SettingsController@updateUser');
I have a very simple SettingsController with a single method called updateUser
.
The udpateUser
first validates the incoming data. The name and email are required fields. In addition, the email of the user should be unique on Cronhub. I identify users based on their emails so I can’t have two users with the same email.
Then, the method makes the actual update of the user fields and returns the new authenticated user in a JSON format.
Here is how I’ve approached testing this controller in unit tests.
What I cared in my tests was to make sure that updateUser
updates email and name fields of the user and validation part of the method works as expected. I have 3 unit tests for each scenario.
Here we go all tests pass and I can continue building Cronhub with high confidence.
I hope you liked this quick tutorial. If you did, say hi to me on Twitter.
Checkout Cronhub that makes it very easy to monitor all your cronjobs in a beautiful dashboard.