Technology Blog

Look deep into latest news and innovations happening in the Tech industry with our highly informational blog.

Laravel Dusk: browser automation & PHP to programmatically surf the web

hkis
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

Once Dusk is installed, you should register the Laravel\Dusk\DuskServiceProvider service provider. Typically, this will be done automatically via Laravel’s automatic service provider registration.

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

Programmatically test applications

Laravel Dusk is a powerful browser automation tool for Laravel. With Dusk you can programmatically test your own applications or visit any website on the internet using a real Chrome browser. Using Dusk you can automate repetitive tasks, scrape information from other sites or test to make sure your app always works in the browser. In this tutorial we’ll go through how to create a job, login to a mythical website and click around.

Create a new Laravel app:

$ laravel new dusk-scraper
$ composer require --dev laravel/dusk
$ php artisan dusk:install
Dusk scaffolding installed successfully.

In the tests/DuskTestCase.php file that Laravel generated you will have a call to startChromeDriver in the prepare function (below). The prepare function gets called before the Dusk test is executed. It’s an abstract class so probably not a good place for us to put our code. We can make a new fresh dusk test case that extends the DuskTestCase with an Artisan command:

$ php artisan dusk:make ScrapeTheWebTest

This file (ScrapeTheWeb.php) will appear in tests/Browser directory. You can run the test with another Artisan command:

$ php artisan dusk-scraper

Right now it does not do anything. Here is the code to login to a website and click some buttons:

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class ScrapeTheWebTest extends DuskTestCase
{

    private $order_ids;

    public function __construct($name = null, array $data = [], $dataName = '')
    {
        parent::__construct($name, $data, $dataName);

        $this->user_ids = [
            1,
            2,
            3,
        ];
    }

    /** @test */
    public function loginAndClickButton()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('https://website.com/login')
                    ->type('input .usernameField', env('USERNAME'))
                    ->type('input .passwordField', env('PASSWORD'))
                    ->click('#login')
                    ->waitForText('Orders');
            @foreach($this->user_ids as $user_id)
            {
                 $browser->visit('https://website.com/users/' . $user_id)
                    ->waitForText('This is protected page')
                    ->click('button .button-im-looking-4')
                    ->waitForText('Page after the button')
                    ->click('.another #button')
                    ->pause(4000);
            }

        });
    }
}

We’m using environment variables to store the values for username and password so in case they are sensitive you don’t have to check them in to version control. To find elements on the page use CSS selectors and browser devtools to target specific elements. We filter through some custom numbers and visit websites dynamically based on this data.

Your tests will run in the terminal with the php artisan dusk command. The fun really comes in when you see the browser perform the actions you specify. By default Laravel Dusk runs what’s called a headless browser that you won’t be able to watch. To watch the browser perform actions head to DuskTestCase.php that our ScrapeTheWebTest inherits from. Once there remove the --headless option:

/**
 * Create the RemoteWebDriver instance.
 *
 * @return \Facebook\WebDriver\Remote\RemoteWebDriver
 */
protected function driver()
{
    $options = (new ChromeOptions)->addArguments([
        '--disable-gpu',
        //'--headless'
    ]);

    return RemoteWebDriver::create(
        'https://localhost:9515', DesiredCapabilities::chrome()->setCapability(
            ChromeOptions::CAPABILITY, $options
        )
    );
}

With the headless option removed you can run the tests and watch the browser perform the actions that you specified! From this command you can use the full power of Laravel to create database records, trigger jobs, update data or anything else you can think of.

For more Information and to build a website using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.

To develop the custom website using Laravel, please visit our technology page

Content Source:

  1. medium.com
  2. laravel.com