Search code examples
laravellaravel-5laravel-5.5laravel-dusklaravel-dusk2

Why can I not use a body class selector with Laravel Dusk?


I am using Laravel 5.5 and Dusk 2.0. I have the following html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body class="my-body-class" id="my-body-div">
    <div class="my-content-class" id="my-content-div">
        Content goes here.
    </div>
</body>
</html>

Here's my Dusk test.

public function testBasicExample()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('/test/admin-fixed-layout');
        $this->assertNotNull($browser->element('.my-content-class'));
        $this->assertNotNull($browser->element('#my-content-div'));
        // $this->assertNotNull($browser->element('.my-body-class'));
        $this->assertNotNull($browser->element('#my-body-div'));
    });
}

If I un-comment the assertion that uses the body class selector, the test fails. Why?


Solution

  • This is because by default prefix is set to body:

    public function __construct($driver, $prefix = 'body')
    {
        $this->driver = $driver;
        $this->prefix = trim($prefix);
    }
    

    in Laravel\Dusk\ElementResolver class.

    If you really need to change this (but probably there is no point), you can add the following method into Tests/DuskTestCase class:

    protected function newBrowser($driver)
    {
        return new \Laravel\Dusk\Browser($driver, new \Laravel\Dusk\ElementResolver($driver, ''));
    }
    

    This will override default browser and pass empty prefix instead of default body prefix