Laravel Dusk is Laravel’s expressive, easy-to-use, and powerful browser test automation tool. Dusk allows you to test javascript-driven applications programmatically. I often run into limitations when writing test cases using Dusk. In this article, I share some of these situations and how to overcome them.

1. Fill in the hidden fields

When testing some JS components (such as autocomplete, date pickers, etc.), you may need to write action simulation operations to interact with those components. Most of these components end up saving values in hidden fields. It might be more convenient to fill in the values directly into the hidden fields. This prevents unstable testing and ensures that we don’t test things we don’t own/control (third-party components).

Although Laravel Dusk doesn’t give us a method like $Browser ->fillHidden($field, $value), we can use Dusk Browser Macros to do it.

// Add the following code to the Browser in serviceprovider.php ::macro('fillHidden'.function ($name , $value) {
    $this->script("document.getElementsByName('$name')[0].value = '$value'");
    return $this; }); // Then you can use /** @ like thistest */
public function fill_hidden_fields()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('https://website.com/form') - >type('input.name'.$name) - >type('input.address'.$address)
                ->fillHidden('checkin_date'.$date)
                ->click('#Submit') - >waitForText('Orders');
    });
}
Copy the code

2. Simulate HTML geolocation


I once had to test a page that required the HTML site to provide a geographic location so that it could display some results. There were no direct mock methods available, so I had to override the getCurrentPosition method, which would eventually be called by the page.


/ * * @test */
public function test_geo_location()
{
    $faker = Faker\Factory::create();
    $latitude = $faker->latitude;
    $longitude = $faker->longitude;

    $this->browse(function (Browser $browser) use($latitude.$longitude) {
        $browser->visit(new Homepage)
            ->assertOnPage();

        $browser->driver->executeScript(
            "window.navigator.geolocation.getCurrentPosition = function(onSuccessCallback) {
                var position = {
                    'coords': { 'latitude': {$latitude}, 'longitude': {$longitude}}}; onSuccessCallback(position); }"
        );

        $browser->click('#geolocate-button')
                ->assertSee('Longitude: $longitude')
                ->assertSee('Latitude: Latitude')}); }Copy the code

3. Use XPath selectors


Sometimes I run into situations where I can’t use CSS selectors to locate elements. This usually happens in dynamic tables, or in third-party JS components that I can’t modify. However, Laravel Dusk does not directly support XPath selectors and often requires access to a basic WebDriver instance.

$browser->driver->findElement( WebDriverBy::xpath("//table[@class='x-grid3-row-table']/tbody/tr/td/div/a[contains(text(),'$value')]") )
                ->click();

Copy the code

The only problem with this approach is that it is possible to end $browser chain-calling.*


4. Full page screenshots

Laravel Dusks provided us with a screen shot of the failed test, which was very helpful in understanding why the test failed. However, sometimes the wrong or problematic element may be outside the display area of the screen.

To create full screenshots in Laravel Dusk, we must create a captureFailuresFor() method in our tests \ dusktestCase.php, It will cover a method originally defined in Laravel\Dusk\Concerns\ProvidesBrowser.

protected function captureFailuresFor($browsers)
{
    $browsers->each(function (Browser $browser.$key) {
        $body = $browser->driver->findElement(WebDriverBy::tagName('body'));
        if(! empty($body)) {
            $currentSize = $body->getSize();
            $size = new WebDriverDimension($currentSize->getWidth(), $currentSize->getHeight());
            $browser->driver->manage()->window()->setSize($size);
        }
        $name = str_replace('\ \'.'_', get_class($this)).'_'.$this->getName(false);

        $browser->screenshot('failure-'.$name.The '-'.$key);
    });
}Copy the code

Now, whenever we call $browser-> Screenshot (‘$shotname’), we will get a complete screenshot when an error occurs


5. Access the browser error log

There’s nothing wrong with that, just something I found interesting. We can access the browser console log by calling $browser-> Driver -> Manage ()->getLog(‘ browser ‘).


This returns a series of logs in the browser console. For example, it can be useful for testing where there are no javascript errors on the page.


@test
public function no_browser_errors()
{
    $this->browse(function ($browser) {
        $this->assertEmpty($browser->driver->manage()->getLog('browser'));
    });
}
Copy the code

Note, however, that it does not contain the output of the console.log call

To learn more, please visit:

Tencent T3-T4 standard boutique PHP architect tutorial directory directory, as long as you finish the guarantee salary rise a step (continue to update)


I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced, and they have no sense of direction when writing too many business codes. I have sorted out some information, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripting, Docker, microservices, Nginx, etc.