LARAVEL

Laravel Dusk Browser Testing

March 15, 2024 14 min read

Introduction

Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. Dusk allows you to test your JavaScript-powered applications and perform end-to-end testing in a real browser.

Installation

Install Dusk via Composer:

composer require --dev laravel/dusk

Install the Chrome Driver:

php artisan dusk:install

First Test

Create your first Dusk test:

php artisan dusk:make ExampleTest

Write a basic test:

namespace Tests\Browser;

use Laravel\Dusk\Browser;
use Tests\DuskTestCase;

class ExampleTest extends DuskTestCase
{
    public function test_basic_example()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                ->assertSee('Laravel');
        });
    }
}

Browser Interactions

public function test_form_submission()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('/contact')
            ->type('name', 'John Doe')
            ->type('email', 'john@example.com')
            ->type('message', 'Hello World')
            ->press('Submit')
            ->assertPathIs('/thank-you');
    });
}

More interactions:

$browser->click('#button')
    ->check('.checkbox')
    ->select('.dropdown', 'option')
    ->attach('.file-input', 'path/to/file.jpg')
    ->scrollIntoView('.footer')
    ->hover('.menu-item');

Authentication Testing

public function test_user_login()
{
    $user = User::factory()->create([
        'email' => 'test@example.com',
    ]);

    $this->browse(function (Browser $browser) use ($user) {
        $browser->visit('/login')
            ->type('email', $user->email)
            ->type('password', 'password')
            ->press('Login')
            ->assertPathIs('/dashboard')
            ->assertAuthenticated();
    });
}

Assertions

$browser->assertTitle('Home Page')
    ->assertTitleContains('Home')
    ->assertPathIs('/home')
    ->assertRouteIs('home')
    ->assertSee('Welcome')
    ->assertSeeIn('.title', 'Welcome')
    ->assertDontSee('Error')
    ->assertVisible('.modal')
    ->assertMissing('.loading')
    ->assertEnabled('.input')
    ->assertDisabled('.button')
    ->assertValue('.email', 'test@example.com')
    ->assertChecked('.checkbox')
    ->assertRadioSelected('.shipping', 'express');

CI Integration

Configure Dusk for CI in phpunit.xml:

<php>
    <env name="DUSK_DRIVER" value="chrome"/>
    <env name="DUSK_HEADLESS" value="true"/>
</php>

Run tests in CI:

php artisan dusk --headless

Summary

Laravel Dusk provides powerful browser automation for testing your applications. With its expressive API, you can write comprehensive end-to-end tests that verify your JavaScript interactions work correctly.

For more information, check out our other tutorials on Livewire and CI/CD Pipeline.