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:

  1. composer require --dev laravel/dusk

{note} 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:

  1. 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:

  1. 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:

  1. php artisan dusk:fails

Managing ChromeDriver Installations

If you would like to install a different version of ChromeDriver than what is included with Laravel Dusk, you may use the dusk:chrome-driver command:

  1. # Install the latest version of ChromeDriver for your OS...
  2. php artisan dusk:chrome-driver
  3. # Install a given version of ChromeDriver for your OS...
  4. php artisan dusk:chrome-driver 74
  5. # Install a given version of ChromeDriver for all supported OSs...
  6. php artisan dusk:chrome-driver --all

{note} Dusk requires the chromedriver binaries to be executable. If you're having problems running Dusk, you should 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:

  1. /**
  2. * Prepare for Dusk test execution.
  3. *
  4. * @beforeClass
  5. * @return void
  6. */
  7. public static function prepare()
  8. {
  9. // static::startChromeDriver();
  10. }

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:

  1. /**
  2. * Create the RemoteWebDriver instance.
  3. *
  4. * @return \Facebook\WebDriver\Remote\RemoteWebDriver
  5. */
  6. protected function driver()
  7. {
  8. return RemoteWebDriver::create(
  9. 'http://localhost:4444/wd/hub', DesiredCapabilities::phantomjs()
  10. );
  11. }

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:

  1. php artisan dusk:make LoginTest

Running Tests

To run your browser tests, use the dusk Artisan command:

  1. 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:

  1. 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:

  1. 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:

  1. /**
  2. * Prepare for Dusk test execution.
  3. *
  4. * @beforeClass
  5. * @return void
  6. */
  7. public static function prepare()
  8. {
  9. // static::startChromeDriver();
  10. }

In addition, if you start ChromeDriver on a port other than 9515, you should modify the driver method of the same class:

  1. /**
  2. * Create the RemoteWebDriver instance.
  3. *
  4. * @return \Facebook\WebDriver\Remote\RemoteWebDriver
  5. */
  6. protected function driver()
  7. {
  8. return RemoteWebDriver::create(
  9. 'http://localhost:9515', DesiredCapabilities::chrome()
  10. );
  11. }

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:

  1. <?php
  2. namespace Tests\Browser;
  3. use App\User;
  4. use Illuminate\Foundation\Testing\DatabaseMigrations;
  5. use Laravel\Dusk\Chrome;
  6. use Tests\DuskTestCase;
  7. class ExampleTest extends DuskTestCase
  8. {
  9. use DatabaseMigrations;
  10. /**
  11. * A basic browser test example.
  12. *
  13. * @return void
  14. */
  15. public function testBasicExample()
  16. {
  17. $user = factory(User::class)->create([
  18. 'email' => '[email protected]',
  19. ]);
  20. $this->browse(function ($browser) use ($user) {
  21. $browser->visit('/login')
  22. ->type('email', $user->email)
  23. ->type('password', 'password')
  24. ->press('Login')
  25. ->assertPathIs('/home');
  26. });
  27. }
  28. }

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.

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:

  1. $this->browse(function ($first, $second) {
  2. $first->loginAs(User::find(1))
  3. ->visit('/home')
  4. ->waitForText('Message');
  5. $second->loginAs(User::find(2))
  6. ->visit('/home')
  7. ->waitForText('Message')
  8. ->type('message', 'Hey Taylor')
  9. ->press('Send');
  10. $first->waitForText('Hey Taylor')
  11. ->assertSee('Jeffrey Way');
  12. });

Resizing Browser Windows

You may use the resize method to adjust the size of the browser window:

  1. $browser->resize(1920, 1080);

The maximize method may be used to maximize the browser window:

  1. $browser->maximize();

The fitContent method will resize the browser window to match the size of the content:

  1. $browser->fitContent();

When a test fails, Dusk will automatically resize the browser to fit the content prior to taking a screenshot. You may disable this feature by calling the disableFitOnFailure method within your test:

  1. $browser->disableFitOnFailure();

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:

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\ServiceProvider;
  4. use Laravel\Dusk\Browser;
  5. class DuskServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Register the Dusk's browser macros.
  9. *
  10. * @return void
  11. */
  12. public function boot()
  13. {
  14. Browser::macro('scrollToElement', function ($element = null) {
  15. $this->script("$('html, body').animate({ scrollTop: $('$element').offset().top }, 0);");
  16. return $this;
  17. });
  18. }
  19. }

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:

  1. $this->browse(function ($browser) use ($user) {
  2. $browser->visit('/pay')
  3. ->scrollToElement('#credit-card-details')
  4. ->assertSee('Enter Credit Card Details');
  5. });

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:

  1. $this->browse(function ($first, $second) {
  2. $first->loginAs(User::find(1))
  3. ->visit('/home');
  4. });

{note} 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:

  1. <?php
  2. namespace Tests\Browser;
  3. use App\User;
  4. use Illuminate\Foundation\Testing\DatabaseMigrations;
  5. use Laravel\Dusk\Chrome;
  6. use Tests\DuskTestCase;
  7. class ExampleTest extends DuskTestCase
  8. {
  9. use DatabaseMigrations;
  10. }

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:

  1. // HTML...
  2. <button>Login</button>
  3. // Test...
  4. $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:

  1. // HTML...
  2. <button dusk="login-button">Login</button>
  3. // Test...
  4. $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:

  1. $browser->clickLink($linkText);

{note} 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:

  1. // Retrieve the value...
  2. $value = $browser->value('selector');
  3. // Set the value...
  4. $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:

  1. $text = $browser->text('selector');

Retrieving Attributes

Finally, the attribute method may be used to retrieve an attribute of an element matching the given selector:

  1. $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:

  1. $browser->type('email', '[email protected]');

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:

  1. $browser->type('tags', 'foo')
  2. ->append('tags', ', bar, baz');

You may clear the value of an input using the clear method:

  1. $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:

  1. $browser->select('size', 'Large');

You may select a random option by omitting the second parameter:

  1. $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:

  1. $browser->check('terms');
  2. $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:

  1. $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:

  1. $browser->attach('photo', __DIR__.'/photos/me.png');

{note} 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:

  1. $browser->keys('selector', ['{shift}', 'taylor'], 'otwell');

You may even send a "hot key" to the primary CSS selector that contains your application:

  1. $browser->keys('.app', ['{command}', 'j']);

{tip} 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:

  1. $browser->click('.selector');

Mouseover

The mouseover method may be used when you need to move the mouse over an element matching the given selector:

  1. $browser->mouseover('.selector');

Drag & Drop

The drag method may be used to drag an element matching the given selector to another element:

  1. $browser->drag('.from-selector', '.to-selector');

Or, you may drag an element in a single direction:

  1. $browser->dragLeft('.selector', 10);
  2. $browser->dragRight('.selector', 10);
  3. $browser->dragUp('.selector', 10);
  4. $browser->dragDown('.selector', 10);

JavaScript Dialogs

Dusk provides various methods to interact with JavaScript Dialogs:

  1. // Wait for a dialog to appear:
  2. $browser->waitForDialog($seconds = null);
  3. // Assert that a dialog has been displayed and that its message matches the given value:
  4. $browser->assertDialogOpened('value');
  5. // Type the given value in an open JavaScript prompt dialog:
  6. $browser->typeInDialog('Hello World');

To close an opened JavaScript Dialog, clicking the OK button:

  1. $browser->acceptDialog();

To close an opened JavaScript Dialog, clicking the Cancel button (for a confirmation dialog only):

  1. $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:

  1. $browser->with('.table', function ($table) {
  2. $table->assertSee('Hello World')
  3. ->clickLink('Delete');
  4. });

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:

  1. $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:

  1. // Wait a maximum of five seconds for the selector...
  2. $browser->waitFor('.selector');
  3. // Wait a maximum of one second for the selector...
  4. $browser->waitFor('.selector', 1);

You may also wait until the given selector is missing from the page:

  1. $browser->waitUntilMissing('.selector');
  2. $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:

  1. $browser->whenAvailable('.modal', function ($modal) {
  2. $modal->assertSee('Hello World')
  3. ->press('OK');
  4. });

Waiting For Text

The waitForText method may be used to wait until the given text is displayed on the page:

  1. // Wait a maximum of five seconds for the text...
  2. $browser->waitForText('Hello World');
  3. // Wait a maximum of one second for the text...
  4. $browser->waitForText('Hello World', 1);

You may use the waitUntilMissingText method to wait until the displayed text has been removed from the page:

  1. // Wait a maximum of five seconds for the text to be removed...
  2. $browser->waitUntilMissingText('Hello World');
  3. // Wait a maximum of one second for the text to be removed...
  4. $browser->waitUntilMissingText('Hello World', 1);

Waiting For Links

The waitForLink method may be used to wait until the given link text is displayed on the page:

  1. // Wait a maximum of five seconds for the link...
  2. $browser->waitForLink('Create');
  3. // Wait a maximum of one second for the link...
  4. $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:

  1. $browser->waitForLocation('/secret');

You may also wait for a named route's location:

  1. $browser->waitForRoute($routeName, $parameters);

Waiting for Page Reloads

If you need to make assertions after a page has been reloaded, use the waitForReload method:

  1. $browser->click('.some-action')
  2. ->waitForReload()
  3. ->assertSee('something');

Waiting On JavaScript Expressions

Sometimes you may wish to pause the execution of a test until a given JavaScript expression evaluates to true. You may easily accomplish this using the waitUntil method. When passing an expression to this method, you do not need to include the return keyword or an ending semi-colon:

  1. // Wait a maximum of five seconds for the expression to be true...
  2. $browser->waitUntil('App.dataLoaded');
  3. $browser->waitUntil('App.data.servers.length > 0');
  4. // Wait a maximum of one second for the expression to be true...
  5. $browser->waitUntil('App.data.servers.length > 0', 1);

Waiting On Vue Expressions

The following methods may be used to wait until a given Vue component attribute has a given value:

  1. // Wait until the component attribute contains the given value...
  2. $browser->waitUntilVue('user.name', 'Taylor', '@user');
  3. // Wait until the component attribute doesn't contain the given value...
  4. $browser->waitUntilVueIsNot('user.name', null, '@user');

Waiting With A Callback

Many of the "wait" methods in Dusk rely on the underlying waitUsing method. You may use this method directly to wait for a given callback to return true. The waitUsing method accepts the maximum number of seconds to wait, the interval at which the Closure should be evaluated, the Closure, and an optional failure message:

  1. $browser->waitUsing(10, 1, function () use ($something) {
  2. return $something->isReady();
  3. }, "Something wasn't ready in time.");

Making Vue Assertions

Dusk even allows you to make assertions on the state of Vue component data. For example, imagine your application contains the following Vue component:

  1. // HTML...
  2. <profile dusk="profile-component"></profile>
  3. // Component Definition...
  4. Vue.component('profile', {
  5. template: '<div>{{ user.name }}</div>',
  6. data: function () {
  7. return {
  8. user: {
  9. name: 'Taylor'
  10. }
  11. };
  12. }
  13. });

You may assert on the state of the Vue component like so:

  1. /**
  2. * A basic Vue test example.
  3. *
  4. * @return void
  5. */
  6. public function testVue()
  7. {
  8. $this->browse(function (Browser $browser) {
  9. $browser->visit('/')
  10. ->assertVue('user.name', 'Taylor', '@profile-component');
  11. });
  12. }

Available Assertions

Dusk provides a variety of assertions that you may make against your application. All of the available assertions are documented in the list below:

assertTitleassertTitleContainsassertUrlIsassertSchemeIsassertSchemeIsNotassertHostIsassertHostIsNotassertPortIsassertPortIsNotassertPathBeginsWithassertPathIsassertPathIsNotassertRouteIsassertQueryStringHasassertQueryStringMissingassertFragmentIsassertFragmentBeginsWithassertFragmentIsNotassertHasCookieassertCookieMissingassertCookieValueassertPlainCookieValueassertSeeassertDontSeeassertSeeInassertDontSeeInassertSourceHasassertSourceMissingassertSeeLinkassertDontSeeLinkassertInputValueassertInputValueIsNotassertCheckedassertNotCheckedassertRadioSelectedassertRadioNotSelectedassertSelectedassertNotSelectedassertSelectHasOptionsassertSelectMissingOptionsassertSelectHasOptionassertValueassertVisibleassertPresentassertMissingassertDialogOpenedassertEnabledassertDisabledassertButtonEnabledassertButtonDisabledassertFocusedassertNotFocusedassertVueassertVueIsNotassertVueContainsassertVueDoesNotContain

assertTitle

Assert that the page title matches the given text:

  1. $browser->assertTitle($title);

assertTitleContains

Assert that the page title contains the given text:

  1. $browser->assertTitleContains($title);

assertUrlIs

Assert that the current URL (without the query string) matches the given string:

  1. $browser->assertUrlIs($url);

assertSchemeIs

Assert that the current URL scheme matches the given scheme:

  1. $browser->assertSchemeIs($scheme);

assertSchemeIsNot

Assert that the current URL scheme does not match the given scheme:

  1. $browser->assertSchemeIsNot($scheme);

assertHostIs

Assert that the current URL host matches the given host:

  1. $browser->assertHostIs($host);

assertHostIsNot

Assert that the current URL host does not match the given host:

  1. $browser->assertHostIsNot($host);

assertPortIs

Assert that the current URL port matches the given port:

  1. $browser->assertPortIs($port);

assertPortIsNot

Assert that the current URL port does not match the given port:

  1. $browser->assertPortIsNot($port);

assertPathBeginsWith

Assert that the current URL path begins with the given path:

  1. $browser->assertPathBeginsWith($path);

assertPathIs

Assert that the current path matches the given path:

  1. $browser->assertPathIs('/home');

assertPathIsNot

Assert that the current path does not match the given path:

  1. $browser->assertPathIsNot('/home');

assertRouteIs

Assert that the current URL matches the given named route's URL:

  1. $browser->assertRouteIs($name, $parameters);

assertQueryStringHas

Assert that the given query string parameter is present:

  1. $browser->assertQueryStringHas($name);

Assert that the given query string parameter is present and has a given value:

  1. $browser->assertQueryStringHas($name, $value);

assertQueryStringMissing

Assert that the given query string parameter is missing:

  1. $browser->assertQueryStringMissing($name);

assertFragmentIs

Assert that the current fragment matches the given fragment:

  1. $browser->assertFragmentIs('anchor');

assertFragmentBeginsWith

Assert that the current fragment begins with the given fragment:

  1. $browser->assertFragmentBeginsWith('anchor');

assertFragmentIsNot

Assert that the current fragment does not match the given fragment:

  1. $browser->assertFragmentIsNot('anchor');

assertHasCookie

Assert that the given cookie is present:

  1. $browser->assertHasCookie($name);

assertCookieMissing

Assert that the given cookie is not present:

  1. $browser->assertCookieMissing($name);

assertCookieValue

Assert that a cookie has a given value:

  1. $browser->assertCookieValue($name, $value);

assertPlainCookieValue

Assert that an unencrypted cookie has a given value:

  1. $browser->assertPlainCookieValue($name, $value);

assertSee

Assert that the given text is present on the page:

  1. $browser->assertSee($text);

assertDontSee

Assert that the given text is not present on the page:

  1. $browser->assertDontSee($text);

assertSeeIn

Assert that the given text is present within the selector:

  1. $browser->assertSeeIn($selector, $text);

assertDontSeeIn

Assert that the given text is not present within the selector:

  1. $browser->assertDontSeeIn($selector, $text);

assertSourceHas

Assert that the given source code is present on the page:

  1. $browser->assertSourceHas($code);

assertSourceMissing

Assert that the given source code is not present on the page:

  1. $browser->assertSourceMissing($code);

assertSeeLink

Assert that the given link is present on the page:

  1. $browser->assertSeeLink($linkText);

assertDontSeeLink

Assert that the given link is not present on the page:

  1. $browser->assertDontSeeLink($linkText);

assertInputValue

Assert that the given input field has the given value:

  1. $browser->assertInputValue($field, $value);

assertInputValueIsNot

Assert that the given input field does not have the given value:

  1. $browser->assertInputValueIsNot($field, $value);

assertChecked

Assert that the given checkbox is checked:

  1. $browser->assertChecked($field);

assertNotChecked

Assert that the given checkbox is not checked:

  1. $browser->assertNotChecked($field);

assertRadioSelected

Assert that the given radio field is selected:

  1. $browser->assertRadioSelected($field, $value);

assertRadioNotSelected

Assert that the given radio field is not selected:

  1. $browser->assertRadioNotSelected($field, $value);

assertSelected

Assert that the given dropdown has the given value selected:

  1. $browser->assertSelected($field, $value);

assertNotSelected

Assert that the given dropdown does not have the given value selected:

  1. $browser->assertNotSelected($field, $value);

assertSelectHasOptions

Assert that the given array of values are available to be selected:

  1. $browser->assertSelectHasOptions($field, $values);

assertSelectMissingOptions

Assert that the given array of values are not available to be selected:

  1. $browser->assertSelectMissingOptions($field, $values);

assertSelectHasOption

Assert that the given value is available to be selected on the given field:

  1. $browser->assertSelectHasOption($field, $value);

assertValue

Assert that the element matching the given selector has the given value:

  1. $browser->assertValue($selector, $value);

assertVisible

Assert that the element matching the given selector is visible:

  1. $browser->assertVisible($selector);

assertPresent

Assert that the element matching the given selector is present:

  1. $browser->assertPresent($selector);

assertMissing

Assert that the element matching the given selector is not visible:

  1. $browser->assertMissing($selector);

assertDialogOpened

Assert that a JavaScript dialog with the given message has been opened:

  1. $browser->assertDialogOpened($message);

assertEnabled

Assert that the given field is enabled:

  1. $browser->assertEnabled($field);

assertDisabled

Assert that the given field is disabled:

  1. $browser->assertDisabled($field);

assertButtonEnabled

Assert that the given button is enabled:

  1. $browser->assertButtonEnabled($button);

assertButtonDisabled

Assert that the given button is disabled:

  1. $browser->assertButtonDisabled($button);

assertFocused

Assert that the given field is focused:

  1. $browser->assertFocused($field);

assertNotFocused

Assert that the given field is not focused:

  1. $browser->assertNotFocused($field);

assertVue

Assert that a given Vue component data property matches the given value:

  1. $browser->assertVue($property, $value, $componentSelector = null);

assertVueIsNot

Assert that a given Vue component data property does not match the given value:

  1. $browser->assertVueIsNot($property, $value, $componentSelector = null);

assertVueContains

Assert that a given Vue component data property is an array and contains the given value:

  1. $browser->assertVueContains($property, $value, $componentSelector = null);

assertVueDoesNotContain

Assert that a given Vue component data property is an array and does not contain the given value:

  1. $browser->assertVueDoesNotContain($property, $value, $componentSelector = null);

Pages

Sometimes, tests require several complicated actions to be performed in sequence. This can make your tests harder to read and understand. Pages allow you to define expressive actions that may then be performed on a given page using a single method. Pages also allow you to define short-cuts to common selectors for your application or a single page.

Generating Pages

To generate a page object, use the dusk:page Artisan command. All page objects will be placed in the tests/Browser/Pages directory:

  1. php artisan dusk:page Login

Configuring Pages

By default, pages have three methods: url, assert, and elements. We will discuss the url and assert methods now. The elements method will be discussed in more detail below.

The url Method

The url method should return the path of the URL that represents the page. Dusk will use this URL when navigating to the page in the browser:

  1. /**
  2. * Get the URL for the page.
  3. *
  4. * @return string
  5. */
  6. public function url()
  7. {
  8. return '/login';
  9. }

The assert Method

The assert method may make any assertions necessary to verify that the browser is actually on the given page. Completing this method is not necessary; however, you are free to make these assertions if you wish. These assertions will be run automatically when navigating to the page:

  1. /**
  2. * Assert that the browser is on the page.
  3. *
  4. * @return void
  5. */
  6. public function assert(Browser $browser)
  7. {
  8. $browser->assertPathIs($this->url());
  9. }

Navigating To Pages

Once a page has been configured, you may navigate to it using the visit method:

  1. use Tests\Browser\Pages\Login;
  2. $browser->visit(new Login);

Sometimes you may already be on a given page and need to "load" the page's selectors and methods into the current test context. This is common when pressing a button and being redirected to a given page without explicitly navigating to it. In this situation, you may use the on method to load the page:

  1. use Tests\Browser\Pages\CreatePlaylist;
  2. $browser->visit('/dashboard')
  3. ->clickLink('Create Playlist')
  4. ->on(new CreatePlaylist)
  5. ->assertSee('@create');

Shorthand Selectors

The elements method of pages allows you to define quick, easy-to-remember shortcuts for any CSS selector on your page. For example, let's define a shortcut for the "email" input field of the application's login page:

  1. /**
  2. * Get the element shortcuts for the page.
  3. *
  4. * @return array
  5. */
  6. public function elements()
  7. {
  8. return [
  9. '@email' => 'input[name=email]',
  10. ];
  11. }

Now, you may use this shorthand selector anywhere you would use a full CSS selector:

  1. $browser->type('@email', '[email protected]');

Global Shorthand Selectors

After installing Dusk, a base Page class will be placed in your tests/Browser/Pages directory. This class contains a siteElements method which may be used to define global shorthand selectors that should be available on every page throughout your application:

  1. /**
  2. * Get the global element shortcuts for the site.
  3. *
  4. * @return array
  5. */
  6. public static function siteElements()
  7. {
  8. return [
  9. '@element' => '#selector',
  10. ];
  11. }

Page Methods

In addition to the default methods defined on pages, you may define additional methods which may be used throughout your tests. For example, let's imagine we are building a music management application. A common action for one page of the application might be to create a playlist. Instead of re-writing the logic to create a playlist in each test, you may define a createPlaylist method on a page class:

  1. <?php
  2. namespace Tests\Browser\Pages;
  3. use Laravel\Dusk\Browser;
  4. class Dashboard extends Page
  5. {
  6. // Other page methods...
  7. /**
  8. * Create a new playlist.
  9. *
  10. * @param \Laravel\Dusk\Browser $browser
  11. * @param string $name
  12. * @return void
  13. */
  14. public function createPlaylist(Browser $browser, $name)
  15. {
  16. $browser->type('name', $name)
  17. ->check('share')
  18. ->press('Create Playlist');
  19. }
  20. }

Once the method has been defined, you may use it within any test that utilizes the page. The browser instance will automatically be passed to the page method:

  1. use Tests\Browser\Pages\Dashboard;
  2. $browser->visit(new Dashboard)
  3. ->createPlaylist('My Playlist')
  4. ->assertSee('My Playlist');

Components

Components are similar to Dusk’s “page objects”, but are intended for pieces of UI and functionality that are re-used throughout your application, such as a navigation bar or notification window. As such, components are not bound to specific URLs.

Generating Components

To generate a component, use the dusk:component Artisan command. New components are placed in the tests/Browser/Components directory:

  1. php artisan dusk:component DatePicker

As shown above, a "date picker" is an example of a component that might exist throughout your application on a variety of pages. It can become cumbersome to manually write the browser automation logic to select a date in dozens of tests throughout your test suite. Instead, we can define a Dusk component to represent the date picker, allowing us to encapsulate that logic within the component:

  1. <?php
  2. namespace Tests\Browser\Components;
  3. use Laravel\Dusk\Browser;
  4. use Laravel\Dusk\Component as BaseComponent;
  5. class DatePicker extends BaseComponent
  6. {
  7. /**
  8. * Get the root selector for the component.
  9. *
  10. * @return string
  11. */
  12. public function selector()
  13. {
  14. return '.date-picker';
  15. }
  16. /**
  17. * Assert that the browser page contains the component.
  18. *
  19. * @param Browser $browser
  20. * @return void
  21. */
  22. public function assert(Browser $browser)
  23. {
  24. $browser->assertVisible($this->selector());
  25. }
  26. /**
  27. * Get the element shortcuts for the component.
  28. *
  29. * @return array
  30. */
  31. public function elements()
  32. {
  33. return [
  34. '@date-field' => 'input.datepicker-input',
  35. '@year-list' => 'div > div.datepicker-years',
  36. '@month-list' => 'div > div.datepicker-months',
  37. '@day-list' => 'div > div.datepicker-days',
  38. ];
  39. }
  40. /**
  41. * Select the given date.
  42. *
  43. * @param \Laravel\Dusk\Browser $browser
  44. * @param int $year
  45. * @param int $month
  46. * @param int $day
  47. * @return void
  48. */
  49. public function selectDate($browser, $year, $month, $day)
  50. {
  51. $browser->click('@date-field')
  52. ->within('@year-list', function ($browser) use ($year) {
  53. $browser->click($year);
  54. })
  55. ->within('@month-list', function ($browser) use ($month) {
  56. $browser->click($month);
  57. })
  58. ->within('@day-list', function ($browser) use ($day) {
  59. $browser->click($day);
  60. });
  61. }
  62. }

Using Components

Once the component has been defined, we can easily select a date within the date picker from any test. And, if the logic necessary to select a date changes, we only need to update the component:

  1. <?php
  2. namespace Tests\Browser;
  3. use Illuminate\Foundation\Testing\DatabaseMigrations;
  4. use Laravel\Dusk\Browser;
  5. use Tests\Browser\Components\DatePicker;
  6. use Tests\DuskTestCase;
  7. class ExampleTest extends DuskTestCase
  8. {
  9. /**
  10. * A basic component test example.
  11. *
  12. * @return void
  13. */
  14. public function testBasicExample()
  15. {
  16. $this->browse(function (Browser $browser) {
  17. $browser->visit('/')
  18. ->within(new DatePicker, function ($browser) {
  19. $browser->selectDate(2019, 1, 30);
  20. })
  21. ->assertSee('January');
  22. });
  23. }
  24. }

Continuous Integration

{note} Before adding a continous integration configuration file, ensure that your .env.testing file contains an APP_URL entry with a value of http://127.0.0.1:8000.

CircleCI

If you are using CircleCI to run your Dusk tests, you may use this configuration file as a starting point. Like TravisCI, we will use the php artisan serve command to launch PHP's built-in web server:

  1. version: 2
  2. jobs:
  3. build:
  4. steps:
  5. - run: sudo apt-get install -y libsqlite3-dev
  6. - run: cp .env.testing .env
  7. - run: composer install -n --ignore-platform-reqs
  8. - run: php artisan key:generate
  9. - run: php artisan dusk:chrome-driver
  10. - run: npm install
  11. - run: npm run production
  12. - run: vendor/bin/phpunit
  13. - run:
  14. name: Start Chrome Driver
  15. command: ./vendor/laravel/dusk/bin/chromedriver-linux
  16. background: true
  17. - run:
  18. name: Run Laravel Server
  19. command: php artisan serve
  20. background: true
  21. - run:
  22. name: Run Laravel Dusk Tests
  23. command: php artisan dusk
  24. - store_artifacts:
  25. path: tests/Browser/screenshots

Codeship

To run Dusk tests on Codeship, add the following commands to your Codeship project. These commands are just a starting point and you are free to add additional commands as needed:

  1. phpenv local 7.2
  2. cp .env.testing .env
  3. mkdir -p ./bootstrap/cache
  4. composer install --no-interaction --prefer-dist
  5. php artisan key:generate
  6. php artisan dusk:chrome-driver
  7. nohup bash -c "php artisan serve 2>&1 &" && sleep 5
  8. php artisan dusk

Heroku CI

To run Dusk tests on Heroku CI, add the following Google Chrome buildpack and scripts to your Heroku app.json file:

  1. {
  2. "environments": {
  3. "test": {
  4. "buildpacks": [
  5. { "url": "heroku/php" },
  6. { "url": "https://github.com/heroku/heroku-buildpack-google-chrome" }
  7. ],
  8. "scripts": {
  9. "test-setup": "cp .env.testing .env",
  10. "test": "nohup bash -c './vendor/laravel/dusk/bin/chromedriver-linux > /dev/null 2>&1 &' && nohup bash -c 'php artisan serve > /dev/null 2>&1 &' && php artisan dusk"
  11. }
  12. }
  13. }
  14. }

Travis CI

To run your Dusk tests on Travis CI, use the following .travis.yml configuration. Since Travis CI is not a graphical environment, we will need to take some extra steps in order to launch a Chrome browser. In addition, we will use php artisan serve to launch PHP's built-in web server:

  1. language: php
  2. php:
  3. - 7.3
  4. addons:
  5. chrome: stable
  6. install:
  7. - cp .env.testing .env
  8. - travis_retry composer install --no-interaction --prefer-dist --no-suggest
  9. - php artisan key:generate
  10. - php artisan dusk:chrome-driver
  11. before_script:
  12. - google-chrome-stable --headless --disable-gpu --remote-debugging-port=9222 http://localhost &
  13. - php artisan serve &
  14. script:
  15. - php artisan dusk

GitHub Actions

If you are using Github Actions to run your Dusk tests, you may use this configuration file as a starting point. Like TravisCI, we will use the php artisan serve command to launch PHP's built-in web server:

  1. name: CI
  2. on: [push]
  3. jobs:
  4. dusk-php:
  5. runs-on: ubuntu-latest
  6. steps:
  7. - uses: actions/[email protected]
  8. - name: Prepare The Environment
  9. run: cp .env.example .env
  10. - name: Create Database
  11. run: mysql --user="root" --password="root" -e "CREATE DATABASE my-database character set UTF8mb4 collate utf8mb4_bin;"
  12. - name: Install Composer Dependencies
  13. run: composer install --no-progress --no-suggest --prefer-dist --optimize-autoloader
  14. - name: Generate Application Key
  15. run: php artisan key:generate
  16. - name: Upgrade Chrome Driver
  17. run: php artisan dusk:chrome-driver
  18. - name: Start Chrome Driver
  19. run: ./vendor/laravel/dusk/bin/chromedriver-linux &
  20. - name: Run Laravel Server
  21. run: php artisan serve &
  22. - name: Run Dusk Tests
  23. run: php artisan dusk