Skip to main content

Laravel Dusk Selenium: Running Laravel Dusk Testing Scripts on Online Selenium Grid


Execute your automation test scripts with Selenium WebDriver instantly through LambdaTest which is a cloud-based, cross browser testing tool offering a Selenium Grid consisting 2000+ browsers and browser versions running on real operating systems to pace up automation testing of your web-app or website. In this topic, you will learn how to perform Selenium automation testing with Laravel Dusk on LambdaTest.

By the end of this topic, you will be able to:

  1. Run a sample Laravel Dusk Selenium Test on LambdaTest Automation.
  2. Set up an environment for testing your locally hosted web pages.
  3. Understand & configure desired capabilities for Laravel Dusk Selenium testing.
  4. Explore advanced features of LambdaTest.

Prerequisites To Run Laravel Dusk Testing With Selenium#


All the code samples in this documentation can be found in the Laravel Dusk LambdaTest Repository on Image GitHub. You can either download or clone the repository to quickly run your tests.

Before you begin automation testing with Laravel Dusk Selenium, be ready with the below essentials:

  • Make sure that you have the latest PHP build installed on your system. If you are using a Mac then PHP would be installed by default. For Linux you would need to enter the below command in terminal:
sudo apt-get install curl libcurl3 libcurl3-dev php

For Windows, you can download PHP from here. Also, refer to this documentation for ensuring the accessibility of PHP through Command Prompt(cmd).

  • Install Laravel Dusk Framework using the below command with composer:
$ composer require laravel/dusk

If you don’t have composer installed in your system then click here.

  • Once you have composer installed, you can leverage Composer to download and install Selenium dependencies. For that first create a composer.json file in your directory and add the following code to the json.
// composer.json
{    "name": "laravel/laravel",    "type": "project",    "description": "The Laravel Framework.",    "keywords": [        "framework",        "laravel"    ],    "license": "MIT",    "require": {        "php": "^7.1.3",        "fideloper/proxy": "^4.0",        "laravel/framework": "5.7.*",        "laravel/tinker": "^1.0"    },    "require-dev": {        "beyondcode/laravel-dump-server": "^1.0",        "filp/whoops": "^2.0",        "fzaninotto/faker": "^1.4",        "laravel/dusk": "^4.0",        "mockery/mockery": "^1.0",        "nunomaduro/collision": "^2.0",        "phpunit/phpunit": "^7.0"    },    "config": {        "optimize-autoloader": true,        "preferred-install": "dist",        "sort-packages": true    },    "extra": {        "laravel": {            "dont-discover": []        }    },    "autoload": {        "psr-4": {            "App\\": "app/",            "Tests\\": "tests/"        },        "classmap": [            "database/seeds",            "database/factories",            "tests/TestCase.php"        ]    },    "autoload-dev": {        "psr-4": {            "Tests\\": "tests/"        }    },    "minimum-stability": "dev",    "prefer-stable": true,    "scripts": {        "post-autoload-dump": [            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",            "@php artisan package:discover --ansi"        ],        "post-root-package-install": [            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""        ],        "post-create-project-cmd": [            "@php artisan key:generate --ansi"        ]    }}
  • Setting up project dependencies.
composer installcomposer dump-autoload
  • Check out our GitHub repository for finding all the code references that will be discussed in this topic.

Getting Started With Laravel Dusk Testing On LambdaTest#


First, let us create .env from the example file:

cp .env.example .env
APP_NAME=LaravelAPP_ENV=localAPP_KEY=APP_DEBUG=trueAPP_URL=http://localhost LT_USERNAME="your username" LT_ACCESS_KEY="YOUR_LAMBDATEST_ACCESS_KEY" LOG_CHANNEL=stack DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=homesteadDB_USERNAME=homesteadDB_PASSWORD=secret BROADCAST_DRIVER=logCACHE_DRIVER=fileQUEUE_CONNECTION=syncSESSION_DRIVER=fileSESSION_LIFETIME=120 REDIS_HOST=127.0.0.1REDIS_PASSWORD=nullREDIS_PORT=6379 MAIL_DRIVER=smtpMAIL_HOST=smtp.mailtrap.ioMAIL_PORT=2525MAIL_USERNAME=nullMAIL_PASSWORD=nullMAIL_ENCRYPTION=null PUSHER_APP_ID=PUSHER_APP_KEY=PUSHER_APP_SECRET=PUSHER_APP_CLUSTER=mt1 MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Now we need to replace, LT_USERNAME with your LambdaTest username & LT_ACCESS_KEY with your access key. You can acquire both using LambdaTest Dashboard.

After that, you need to update platform configuration in driver method of tests/DuskTestCase.php, to specify the target where tests should run. (List of supported OS platfrom, Browser, resolutions can be found at LambdaTest Capability Generator

Sample configuration:

//php-laravel-dusk-todo-master\tests\DuskTestCase.php

return RemoteWebDriver::create($url,        DesiredCapabilities::chrome()            ->setCapability("platform", "win10")            ->setCapability("browserName", "chrome")            ->setCapability("version", "71.0")            ->setCapability("resolution", "1024x768")            ->setCapability("build", "LaravelDusk Build")            ->setCapability("name", "LaravelDusk Test")    );

Running Tests On Locally Hosted Web Pages Or Web Apps Using Laravel Dusk Selenium#


You can run Selenium test for your locally hosted webpages or web apps using the LambdaTest Tunnel or UnderPass (GUI Tunnel Application). You will need to do the following for running Selenium test automation for locally or privately hosted projects.

  1. Download and install LambdaTest Tunnel or Underpass in your system.
  2. Define tunnel capability to true in DesiredCapabilities class.
  3. Specify your local testing URL or DNS.

Let us look at each of these steps in detail.

Download & Install LambdaTest Tunnel Or UnderPass#


Download the binary file of:

To install and run LambdaTest Tunnel, you can follow our step-by-step documentation.

Or if you wish to avoid Command Line Interface then you can use the UnderPass application.

underpass

Download:

For more details, refer to the support documentation of UnderPass.

Define Tunnel Capability To True#


After installing and running the LambdaTest Tunnel, you now need to specify the tunnel value to true in your desired capabilities.

return RemoteWebDriver::create($url,            DesiredCapabilities::chrome()                ->setCapability("tunnel", true) // running tests on locally hosted web pages        );

Let us have a look at an example which will validate your LambdaTest credentials for authentication purpose. Later, the code will select the basic capabilities such as OS, browser, browser version and so on. You will find the capabilities in the driver method of tests/DuskTestCase.php on our Laravel Dusk Testing GitHub Repository.

<?php
namespace Tests;
use Laravel\Dusk\TestCase as BaseTestCase;use Facebook\WebDriver\Remote\RemoteWebDriver;use Facebook\WebDriver\Remote\DesiredCapabilities;
abstract class DuskTestCase extends BaseTestCase{    use CreatesApplication;
    /**     * Prepare for Dusk test execution.     *     * @beforeClass     * @return void     */    public static function prepare()    {        // static::startChromeDriver();    }
    /**     * Create the RemoteWebDriver instance.     *     * @return \Facebook\WebDriver\Remote\RemoteWebDriver     */    protected function driver()    {
        $username = env('LT_USERNAME');        $access_key = env('LT_ACCESS_KEY');        $url = "https://".$username.":".$access_key."@hub.lambdatest.com/wd/hub";
        return RemoteWebDriver::create($url,             DesiredCapabilities::chrome()                ->setCapability("platform", "win10")                ->setCapability("browserName", "chrome")                ->setCapability("version", "71.0")                ->setCapability("resolution", "1024x768")                ->setCapability("build", "LaravelDusk Build")                ->setCapability("name", "LaravelDusk Test")        );    }    }

You can easily generate the DesiredCapabilities with our Selenium Capabilities Generator.

Specify Your Local Testing URL Or DNS#


Important Note: 127.0.0.1 IP address won’t work when using tunnel as different browsers exhibit different behaviours. You can use localhost, localhost.lambdatest.com, any custom domain if that’s entered into your etc/hosts file, or you can specify a custom domain that is managed by a custom DNS server, provided that you explicitly pass DNS server details while initiating the tunnel.

To explicitly pass DNS server details through LambdaTest Tunnel you will need to use the --dns argument and pass the local host string i.e. 127.0.0.1:port number as the value while triggering the tunnel.

Note: For PHP Laravel, 127.0.0.1:53 is the default value so you will need to specify that.

The command-syntax would look like:

LT --user {LambdaTest login email} --key {LambdaTest access key} --cui --tunnelName dusk-sample --dns 127.0.0.1:53

Here is an example of this command:

LT --user [email protected].com --key 123asd123 --cui --tunnelName dusk-sample --dns 127.0.0.1:53

To explicitly pass DNS server details through the Underpass application, you will need to go to Advanced settings and provide 127.0.0.1:53 for PHP Laravel as the value for the DNS Server field.

underpass

Test Scenario: Sample To Do App#


You can find all the code files in our Laravel Dusk Testing GitHub Repository.

Let us quickly analyze our test scenario: Visit the Sample To Do App, check the first and second item from the list and add a new item i.e. ‘sampletodotext’. Here is the code file for it.

<?php namespace Tests\Browser; use Tests\DuskTestCase;use Laravel\Dusk\Browser;use Illuminate\Foundation\Testing\DatabaseMigrations; class TodoTest extends DuskTestCase{    /**     * A Dusk test example.     *     * @return void     */    public function testExample()    {        $this->browse(function (Browser $browser) {            $browser->visit('https://lambdatest.github.io/sample-todo-app/')                    ->assertTitleContains('Sample page - lambdatest.com')                    ->check("li1")                    ->check("li3")                    ->type("#sampletodotext", "Let's add new to do item")                    ->press('#addbutton');            sleep(10);        });     }}

Execute The Laravel Dusk Testing Script#


You would need to execute the below command in your terminal/cmd:

php artisan dusk
Last updated on