Laravel Dusk
Introduction
Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. By default, Dusk does not require you to install JDK or Selenium on your machine. Instead, Dusk uses a standalone ChromeDriver installation. However, you are free to utilize any other Selenium compatible driver you wish.
Installation
To get started, you should add the laravel/dusk
Composer dependency to your project:
composer require --dev laravel/dusk:"^5.0"
If you are manually registering Dusk's service provider, you should never register it in your production environment, as doing so could lead to arbitrary users being able to authenticate with your application.
After installing the Dusk package, run the dusk:install
Artisan command:
php artisan dusk:install
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
If you had test failures the last time you ran the dusk
command, you may save time by re-running the failing tests first using the dusk:fails
command:
php artisan dusk:fails
Dusk requires its chromedriver
binaries to be executable. If you're having problems running Dusk, you can ensure the binaries are executable using the following command: chmod -R 0755 vendor/laravel/dusk/bin/
.
Using Other Browsers
By default, Dusk uses Google Chrome and a standalone ChromeDriver installation to run your browser tests. However, you may start your own Selenium server and run your tests against any browser you wish.
To get started, open your tests/DuskTestCase.php
file, which is the base Dusk test case for your application. Within this file, you can remove the call to the startChromeDriver
method. This will stop Dusk from automatically starting the ChromeDriver:
/**
* Prepare for Dusk test execution.
*
* @beforeClass
* @return void
*/
public static function prepare()
{
// static::startChromeDriver();
}
Next, you may modify the driver
method to connect to the URL and port of your choice. In addition, you may modify the "desired capabilities" that should be passed to the WebDriver:
/**
* Create the RemoteWebDriver instance.
*
* @return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
return RemoteWebDriver::create(
'http://localhost:4444/wd/hub', DesiredCapabilities::phantomjs()
);
}
Getting Started
Generating Tests
To generate a Dusk test, use the dusk:make
Artisan command. The generated test will be placed in the tests/Browser
directory:
php artisan dusk:make LoginTest
Running Tests
To run your browser tests, use the dusk
Artisan command:
php artisan dusk
If you had test failures the last time you ran the dusk
command, you may save time by re-running the failing tests first using the dusk:fails
command:
php artisan dusk:fails
The dusk
command accepts any argument that is normally accepted by the PHPUnit test runner, allowing you to only run the tests for a given group, etc:
php artisan dusk --group=foo
Manually Starting ChromeDriver
By default, Dusk will automatically attempt to start ChromeDriver. If this does not work for your particular system, you may manually start ChromeDriver before running the dusk
command. If you choose to start ChromeDriver manually, you should comment out the following line of your tests/DuskTestCase.php
file:
/**
* Prepare for Dusk test execution.
*
* @beforeClass
* @return void
*/
public static function prepare()
{
// static::startChromeDriver();
}
In addition, if you start ChromeDriver on a port other than 9515, you should modify the driver
method of the same class:
/**
* Create the RemoteWebDriver instance.
*
* @return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
return RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::chrome()
);
}
Environment Handling
To force Dusk to use its own environment file when running tests, create a .env.dusk.{environment}
file in the root of your project. For example, if you will be initiating the dusk
command from your local
environment, you should create a .env.dusk.local
file.
When running tests, Dusk will back-up your .env
file and rename your Dusk environment to .env
. Once the tests have completed, your .env
file will be restored.
Creating Browsers
To get started, let's write a test that verifies we can log into our application. After generating a test, we can modify it to navigate to the login page, enter some credentials, and click the "Login" button. To create a browser instance, call the browse
method:
<?php
namespace Tests\Browser;
use App\User;
use Tests\DuskTestCase;
use Laravel\Dusk\Chrome;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class ExampleTest extends DuskTestCase
{
use DatabaseMigrations;
/**
* A basic browser test example.
*
* @return void
*/
public function testBasicExample()
{
$user = factory(User::class)->create([
'email' => 'taylor@laravel.com',
]);
$this->browse(function ($browser) use ($user) {
$browser->visit('/login')
->type('email', $user->email)
->type('password', 'secret')
->press('Login')
->assertPathIs('/home');
});
}
}
As you can see in the example above, the browse
method accepts a callback. A browser instance will automatically be passed to this callback by Dusk and is the main object used to interact with and make assertions against your application.
This test can be used to test the login screen generated by the make:auth
Artisan command.
Creating Multiple Browsers
Sometimes you may need multiple browsers in order to properly carry out a test. For example, multiple browsers may be needed to test a chat screen that interacts with websockets. To create multiple browsers, "ask" for more than one browser in the signature of the callback given to the browse
method:
$this->browse(function ($first, $second) {
$first->loginAs(User::find(1))
->visit('/home')
->waitForText('Message');
$second->loginAs(User::find(2))
->visit('/home')
->waitForText('Message')
->type('message', 'Hey Taylor')
->press('Send');
$first->waitForText('Hey Taylor')
->assertSee('Jeffrey Way');
});
Resizing Browser Windows
You may use the resize
method to adjust the size of the browser window:
$browser->resize(1920, 1080);
The maximize
method may be used to maximize the browser window:
$browser->maximize();
Browser Macros
If you would like to define a custom browser method that you can re-use in a variety of your tests, you may use the macro
method on the Browser
class. Typically, you should call this method from a service provider's boot
method:
<?php
namespace App\Providers;
use Laravel\Dusk\Browser;
use Illuminate\Support\ServiceProvider;
class DuskServiceProvider extends ServiceProvider
{
/**
* Register the Dusk's browser macros.
*
* @return void
*/
public function boot()
{
Browser::macro('scrollToElement', function ($element = null) {
$this->script("$('html, body').animate({ scrollTop: $('$element').offset().top }, 0);");
return $this;
});
}
}
The macro
function accepts a name as its first argument, and a Closure as its second. The macro's Closure will be executed when calling the macro as a method on a Browser
implementation:
$this->browse(function ($browser) use ($user) {
$browser->visit('/pay')
->scrollToElement('#credit-card-details')
->assertSee('Enter Credit Card Details');
});
Authentication
Often, you will be testing pages that require authentication. You can use Dusk's loginAs
method in order to avoid interacting with the login screen during every test. The loginAs
method accepts a user ID or user model instance:
$this->browse(function ($first, $second) {
$first->loginAs(User::find(1))
->visit('/home');
});
After using the loginAs
method, the user session will be maintained for all tests within the file.
Database Migrations
When your test requires migrations, like the authentication example above, you should never use the RefreshDatabase
trait. The RefreshDatabase
trait leverages database transactions which will not be applicable across HTTP requests. Instead, use the DatabaseMigrations
trait:
<?php
namespace Tests\Browser;
use App\User;
use Tests\DuskTestCase;
use Laravel\Dusk\Chrome;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class ExampleTest extends DuskTestCase
{
use DatabaseMigrations;
}
Interacting With Elements
Dusk Selectors
Choosing good CSS selectors for interacting with elements is one of the hardest parts of writing Dusk tests. Over time, frontend changes can cause CSS selectors like the following to break your tests:
// HTML...
<button>Login</button>
// Test...
$browser->click('.login-page .container div > button');
Dusk selectors allow you to focus on writing effective tests rather than remembering CSS selectors. To define a selector, add a dusk
attribute to your HTML element. Then, prefix the selector with @
to manipulate the attached element within a Dusk test:
// HTML...
<button dusk="login-button">Login</button>
// Test...
$browser->click('@login-button');
Clicking Links
To click a link, you may use the clickLink
method on the browser instance. The clickLink
method will click the link that has the given display text:
$browser->clickLink($linkText);
This method interacts with jQuery. If jQuery is not available on the page, Dusk will automatically inject it into the page so it is available for the test's duration.
Text, Values, & Attributes
Retrieving & Setting Values
Dusk provides several methods for interacting with the current display text, value, and attributes of elements on the page. For example, to get the "value" of an element that matches a given selector, use the value
method:
// Retrieve the value...
$value = $browser->value('selector');
// Set the value...
$browser->value('selector', 'value');
Retrieving Text
The text
method may be used to retrieve the display text of an element that matches the given selector:
$text = $browser->text('selector');
Retrieving Attributes
Finally, the attribute
method may be used to retrieve an attribute of an element matching the given selector:
$attribute = $browser->attribute('selector', 'value');
Using Forms
Typing Values
Dusk provides a variety of methods for interacting with forms and input elements. First, let's take a look at an example of typing text into an input field:
$browser->type('email', 'taylor@laravel.com');
Note that, although the method accepts one if necessary, we are not required to pass a CSS selector into the type
method. If a CSS selector is not provided, Dusk will search for an input field with the given name
attribute. Finally, Dusk will attempt to find a textarea
with the given name
attribute.
To append text to a field without clearing its content, you may use the append
method:
$browser->type('tags', 'foo')
->append('tags', ', bar, baz');
You may clear the value of an input using the clear
method:
$browser->clear('email');
Dropdowns
To select a value in a dropdown selection box, you may use the select
method. Like the type
method, the select
method does not require a full CSS selector. When passing a value to the select
method, you should pass the underlying option value instead of the display text:
$browser->select('size', 'Large');
You may select a random option by omitting the second parameter:
$browser->select('size');
Checkboxes
To "check" a checkbox field, you may use the check
method. Like many other input related methods, a full CSS selector is not required. If an exact selector match can't be found, Dusk will search for a checkbox with a matching name
attribute:
$browser->check('terms');
$browser->uncheck('terms');
Radio Buttons
To "select" a radio button option, you may use the radio
method. Like many other input related methods, a full CSS selector is not required. If an exact selector match can't be found, Dusk will search for a radio with matching name
and value
attributes:
$browser->radio('version', 'php7');
Attaching Files
The attach
method may be used to attach a file to a file
input element. Like many other input related methods, a full CSS selector is not required. If an exact selector match can't be found, Dusk will search for a file input with matching name
attribute:
$browser->attach('photo', __DIR__.'/photos/me.png');
The attach function requires the Zip
PHP extension to be installed and enabled on your server.
Using The Keyboard
The keys
method allows you to provide more complex input sequences to a given element than normally allowed by the type
method. For example, you may hold modifier keys entering values. In this example, the shift
key will be held while taylor
is entered into the element matching the given selector. After taylor
is typed, otwell
will be typed without any modifier keys:
$browser->keys('selector', ['{shift}', 'taylor'], 'otwell');
You may even send a "hot key" to the primary CSS selector that contains your application:
$browser->keys('.app', ['{command}', 'j']);
All modifier keys are wrapped in {}
characters, and match the constants defined in the Facebook\WebDriver\WebDriverKeys
class, which can be found on GitHub.
Using The Mouse
Clicking On Elements
The click
method may be used to "click" on an element matching the given selector:
$browser->click('.selector');
Mouseover
The mouseover
method may be used when you need to move the mouse over an element matching the given selector:
$browser->mouseover('.selector');
Drag & Drop
The drag
method may be used to drag an element matching the given selector to another element:
$browser->drag('.from-selector', '.to-selector');
Or, you may drag an element in a single direction:
$browser->dragLeft('.selector', 10);
$browser->dragRight('.selector', 10);
$browser->dragUp('.selector', 10);
$browser->dragDown('.selector', 10);
JavaScript Dialogs
Dusk provides various methods to interact with JavaScript Dialogs:
// Wait for a dialog to appear:
$browser->waitForDialog($seconds = null);
// Assert that a dialog has been displayed and that its message matches the given value:
$browser->assertDialogOpened('value');
// Type the given value in an open JavaScript prompt dialog:
$browser->typeInDialog('Hello World');
To close an opened JavaScript Dialog, clicking the OK button:
$browser->acceptDialog();
To close an opened JavaScript Dialog, clicking the Cancel button (for a confirmation dialog only):
$browser->dismissDialog();
Scoping Selectors
Sometimes you may wish to perform several operations while scoping all of the operations within a given selector. For example, you may wish to assert that some text exists only within a table and then click a button within that table. You may use the with
method to accomplish this. All operations performed within the callback given to the with
method will be scoped to the original selector:
$browser->with('.table', function ($table) {
$table->assertSee('Hello World')
->clickLink('Delete');
});
Waiting For Elements
When testing applications that use JavaScript extensively, it often becomes necessary to "wait" for certain elements or data to be available before proceeding with a test. Dusk makes this a cinch. Using a variety of methods, you may wait for elements to be visible on the page or even wait until a given JavaScript expression evaluates to true
.
Waiting
If you need to pause the test for a given number of milliseconds, use the pause
method:
$browser->pause(1000);
Waiting For Selectors
The waitFor
method may be used to pause the execution of the test until the element matching the given CSS selector is displayed on the page. By default, this will pause the test for a maximum of five seconds before throwing an exception. If necessary, you may pass a custom timeout threshold as the second argument to the method:
// Wait a maximum of five seconds for the selector...
$browser->waitFor('.selector');
// Wait a maximum of one second for the selector...
$browser->waitFor('.selector', 1);
You may also wait until the given selector is missing from the page:
$browser->waitUntilMissing('.selector');
$browser->waitUntilMissing('.selector', 1);
Scoping Selectors When Available
Occasionally, you may wish to wait for a given selector and then interact with the element matching the selector. For example, you may wish to wait until a modal window is available and then press the "OK" button within the modal. The whenAvailable
method may be used in this case. All element operations performed within the given callback will be scoped to the original selector:
$browser->whenAvailable('.modal', function ($modal) {
$modal->assertSee('Hello World')
->press('OK');
});
Waiting For Text
The waitForText
method may be used to wait until the given text is displayed on the page:
// Wait a maximum of five seconds for the text...
$browser->waitForText('Hello World');
// Wait a maximum of one second for the text...
$browser->waitForText('Hello World', 1);
Waiting For Links
The waitForLink
method may be used to wait until the given link text is displayed on the page:
// Wait a maximum of five seconds for the link...
$browser->waitForLink('Create');
// Wait a maximum of one second for the link...
$browser->waitForLink('Create', 1);
Waiting On The Page Location
When making a path assertion such as $browser->assertPathIs('/home')
, the assertion can fail if window.location.pathname
is being updated asynchronously. You may use the waitForLocation
method to wait for the location to be a given value:
$browser->waitForLocation('/secret');
You may also wait for a named route's location:
$browser->waitForRoute($routeName, $parameters);
Waiting for Page Reloads
If you need to make assertions after a page has been reloaded, use the waitForReload
method:
$browser->click('.some-action')
->waitForReload()
->assertSee('something');