Main navigation

From Dusk Till Dawn

Breadcrumb

Writing website tests in Laravel could generally follow a simple algorithm: Write tests -> Run tests (kudos to phpunit) -> evaluate the output message -> Repair or restructure the main code. Generally, while doing unit tests, everything is close to perfect. However, browser tests (feature tests) are a different ball game.

Previously Laravel used the Symfony BrowserKit component to simulate the behaviour of a web browser. This enabled programmers to test their code interactively, by clicking on links, filling forms, asserting that some entity is present on the webpage or not, filling forms etc.

WHAT DOES LARAVEL DUSK DO?

Overtime, with more programmers using JavaScript and AJAX to load their webpages, the BrowserKit became limited. Something had to be done. With the introduction of Laravel 5.4 came the Dusk... the solution to this problem.

Laravel Dusk offers browser automation and testing API at a different level. It is easy to use and highly redolent in its applications while solving the challenge of end-to-end testing of JavaScript applications.

Dusk utilizes ChromeDriver and Facebook PHP-Webdriver for doing end-to-end tests. It can work with any Selenium browser, but it comes with ChromeDriver by default which will save you from installing JDK or Selenium. An additional feature of Dusk is that it saves screenshots of failed tests automatically! You can see what the page looked like and what went wrong.

RUNNING LARAVEL DUSK

Laravel Dusk is installed by adding the Composer dependency “laravel/dusk” to your project. Underneath are screenshots on the processes for Dusk installation.

Installation: Step 1

To get started, you should add the laravel/dusk Composer dependency to your project:

composer require --dev laravel/dusk

Once Dusk is installed, you should register the Laravel\Dusk\DuskServiceProvider service provider. You should register the provider within the register method of your AppServiceProvider in order to limit the environments in which Dusk is available, since it exposes the ability to log in as other users:

A Browser directory will be created within your tests directory and will contain an example test. Next, set the APP_URL environment variable in your .env file. This value should match the URL you use to access your application in a browser.

To run your tests, use the dusk Artisan command. The dusk command accepts any argument that is also accepted by the phpunit command:

php artisan dusk

To run your Dusk test, you will not use PHPUnit directly. Instead, you will call a Dusk artisan command (artisan dusk) which will proxy down to PHPUnit and backup your .env file. Then, it will move the .env.dusk file to be the environment being used for your Dusk test. When finished, it will restore your real .env file back to its place.