Testing views in isolation with Laravel Mojito

  • 3 Min. Read.

With Laravel Mojito you can test your views in isolation with ease.

Install the package

In your Laravel project root, run the following composer command:

Create your first test

With artisan, create a new test:

Add the InteractsWithViews trait, which adds the assertView method to your test

Next up, you can make an assertion on your view, for example assert that the word ‘Mojito’ is present:

Asserting a view contains a word within a specific selector

With Laravel Mojito you can use query selectors like in CSS to make more specific assertions. In the welcome template there is a div with a class ‘links’, and the last link is the one to GitHub:

Let’s say we want to add an assertion that in the welcome template there is a link to GitHub, we would use the following code:

And if we want to make sure the link is correct, we can do it with the hasLink method:

Passing $data to your view

Create a new blade template called title.blade.php and add a variable $title in it:

We want to test our new title.blade.php view, and to do so we have to pass in $data, so the view gets rendered as expected:

Making complex assertions

You can make complex assertions, for example to make sure the first meta tag in the head has an attribute charset with the value of utf-8:

Testing views with HTTP tests

Sometimes testing a view in isolation is not sufficient because of all the logic that gets executed before rendering a view. Assume we have a NameController like so:

When we visit our application at /name/codecaptain, a view would be rendered with the following HTML:

To make an assertion on the view rendered by the controller, we can use HTTP Tests:

The unit test will make an HTTP request to your application, and on the returned response we can run our assertions as if it were an isolated blade template.