Site icon Student Projects Live

Laravel Dusk

Laravel Dusk

Laravel Dusk is an automated browser testing tool.

Imagine you have a website with a form.

Normally:

  1. Open browser
  2. Visit page
  3. Fill form
  4. Click Submit
  5. Check result

Every time you make a change, you repeat these steps.

Laravel Dusk does these steps automatically.

It controls a real browser and acts like a human user.


Real Life Example

Suppose your school website has a student registration form.

Without Dusk:

With Dusk:

Laravel automatically:

All in a few seconds.


Why Use Laravel Dusk?

Benefits:

Saves Time

No need to test manually every time.

Finds Bugs Early

If something breaks, Dusk tells you immediately.

Tests Real User Actions

It tests exactly how users interact with your website.

Useful for Large Projects

When a website has many forms and pages.


Create Laravel Project

Before using Laravel Dusk, we first need to create a Laravel application. If you already have an existing Laravel project, you can skip the Laravel installation steps and continue with the Dusk setup.

Create a New Laravel Project

Open your terminal or command prompt and run:

composer create-project laravel/laravel school-app

Here:

Move Into the Project Directory

cd school-app

Start the Laravel Development Server

php artisan serve

Open the Application

Open your browser and visit:

http://127.0.0.1:8000

If everything is installed correctly, the Laravel welcome page will appear.

What We Learned

In this step, we:

  1. Created a new Laravel project.
  2. Entered the project folder.
  3. Started the Laravel development server.
  4. Opened the application in a browser.

Now that Laravel is running successfully, we can create our student registration form in the next step.


Configure APP_URL

Before creating the form or running Laravel Dusk tests, open the .env file in the root of your Laravel project and make sure the APP_URL value matches the URL used by your Laravel application.

APP_URL=http://127.0.0.1:8000

Laravel Dusk uses the APP_URL value when opening pages during browser tests. For example, when you write:

$browser->visit('/student');

Dusk automatically opens:

http://127.0.0.1:8000/student

If APP_URL is incorrect, Dusk may open the wrong page and fail to find form elements, causing test failures.

After updating the .env file, clear the configuration cache:

php artisan config:clear

Now Laravel and Dusk will use the correct application URL.


Creating a Student Form

We will create a simple form.

Fields:


Step 1: Create Route

Open:

routes/web.php

Add:

use Illuminate\Http\Request;

Route::get('/student', function () {
    return view('student');
});

Route::post('/student', function (Request $request) {
    return back()->with('success', 'Student Registered Successfully');
});

Step 2: Create View

Create file:

resources/views/student.blade.php

Add:

<!DOCTYPE html>
<html>
<head>
    <title>Student Form</title>
</head>
<body>

<h1>Student Registration</h1>

@if(session('success'))
    <p>{{ session('success') }}</p>
@endif

<form method="POST" action="/student">
    @csrf

    <label for="name">Name</label>
    <input
        type="text"
        id="name"
        name="name"
        placeholder="Enter Name" required>

    <br><br>

    <label for="email">Email</label>
    <input
        type="email"
        id="email"
        name="email"
        placeholder="Enter Email" required> 
<br><br>

<label for="password">Password</label>
<input
    type="password"
    id="password"
    name="password"
    placeholder="Enter Password" required>

<br><br>

<label for="gender">Gender</label>
<input type="radio" id="male" name="gender" value="Male" required>
<label for="male">Male</label>

<input type="radio" id="female" name="gender" value="Female" required>
<label for="female">Female</label>

<br><br>

<label for="hobbies">Hobbies</label>
<input type="checkbox" id="reading" name="hobbies[]" value="Reading">
<label for="reading">Reading</label>

<input type="checkbox" id="sports" name="hobbies[]" value="Sports">
<label for="sports">Sports</label>

<input type="checkbox" id="music" name="hobbies[]" value="Music">
<label for="music">Music</label>

<br><br>

<label for="class">Class</label>
<select id="class" name="class" required>
    <option value="">Select Class</option>
    <option value="8">Class 8</option>
    <option value="9">Class 9</option>
    <option value="10">Class 10</option>
</select>

<br><br>

<label for="dob">Date of Birth</label>
<input
    type="date"
    id="dob"
    name="dob" required>

<br><br>

<label for="photo">Upload Photo</label>
<input
    type="file"
    id="photo"
    name="photo" required>

<br><br>

<label for="address">Address</label>
<textarea
    id="address"
    name="address"
    rows="4"
    cols="30"
    placeholder="Enter Address" required></textarea>

    <br><br>

    <button type="submit">
        Register
    </button>
</form>

</body>
</html>

Step 3: Test Form Manually

Open:

http://127.0.0.1:8000/student

Fill:

Name: Niel John
Email: nielsjohn@test.com
Password: Password@123
Gender: Male
Hobbies: Reading, Sports
Class: Class 10
Date of Birth: 2008-05-15
Photo: upload any image
Address: 123 School Street, Chennai, Tamil Nadu

Click:

Register

Success message appears.

Great!

Now we can automate this using Laravel Dusk.


Step 4: Installing Laravel Dusk

Inside project:

composer require --dev laravel/dusk

Install Dusk:

php artisan dusk:install

Laravel creates:

tests/Browser

This folder stores browser tests.


What Happens Internally?

When you run a Laravel Dusk test, Laravel communicates with ChromeDriver, which acts as a bridge between your application and the Chrome browser. Dusk sends commands such as opening a page, typing into form fields, clicking buttons, and checking page content. ChromeDriver receives these commands and performs the actions in a real Chrome browser, just like a human user would. This allows developers to test the complete user experience and ensure that web pages, forms, and interactions work correctly from start to finish.

Dusk uses:

Chrome Browser and ChromeDriver.

ChromeDriver allows Laravel to control Chrome automatically.

Think:

Laravel Dusk
      ↓
ChromeDriver
      ↓
Chrome Browser

Step 5: Creating First Dusk Test

Create test:

php artisan dusk:make StudentFormTest

File created:

tests/Browser/StudentFormTest.php

Step 6: Replace Content

Since our student registration form now contains multiple fields such as password, gender, hobbies, class, date of birth, photo upload, and address, we need to update the Dusk test to interact with all these form elements.

Add the content of tests/Browser/StudentFormTest.php with:

<?php

namespace Tests\Browser;

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

class StudentFormTest extends DuskTestCase
{
    public function test_student_registration()
    {
        $this->browse(function (Browser $browser) {

            $browser->visit('/student')

                    ->type('name', 'Niel John')

                    ->type('email', 'nielsjohn@test.com')

                    ->type('password', 'Password@123')

                    ->radio('gender', 'Male')

                    ->check('hobbies[]', 'Reading')

                    ->check('hobbies[]', 'Sports')

                    ->select('class', '10')

                    ->type('dob', '2008-05-15')

                    ->attach('photo', public_path('favicon.ico'))

                    ->type(
                        'address',
                        '123 School Street, Chennai, Tamil Nadu'
                    )

                    ->press('Register')

                    ->assertSee(
                        'Student Registered Successfully'
                    );
        });
    }
}

What This Test Does

The test performs the same actions that a real student would perform while filling out the registration form:

  1. Opens the Student Registration page.
  2. Enters the student’s name.
  3. Enters the email address.
  4. Enters the password.
  5. Selects the gender radio button.
  6. Selects hobbies using checkboxes.
  7. Chooses a class from the dropdown list.
  8. Enters the date of birth.
  9. Uploads a photo.
  10. Enters the address.
  11. Clicks the Register button.
  12. Verifies that the success message “Student Registered Successfully” appears on the page.

This demonstrates how Laravel Dusk can automate testing of different HTML form elements such as text fields, password fields, radio buttons, checkboxes, dropdowns, file uploads, date inputs, and text areas.


Step 7: Important: Remove the Default Example Test

When Laravel Dusk is installed, it automatically creates a sample test file:

tests/Browser/ExampleTest.php

This test expects the default Laravel welcome page to contain the text “Laravel”. If you have already modified your application or created your own pages, this test may fail and show errors when running Dusk.

Before running your own tests, delete the default example test:

rm tests\Browser\ExampleTest.php

Alternatively, you can update the file to match your application, but deleting it is usually the simplest option when starting with your own Dusk tests.

After removing the default file, Laravel Dusk will execute only the tests that you create, such as StudentFormTest.php.


Running Dusk Test

Run:

php artisan dusk

Dusk:

  1. Opens Chrome
  2. Opens page
  3. Fills form
  4. Clicks button
  5. Checks result
  6. Closes browser

Output:

PASS
StudentFormTest

What If Test Fails?

Example:

Expected:

PASS  Tests\Browser\StudentFormTest
✓ student registration

Tests:    1 passed (1 assertions)
Duration: 23.78s

Actual:

Something Went Wrong

Dusk output:

FAILED

This tells developers something is broken.


Step 8: Useful Dusk Commands

Run all tests:

php artisan dusk

Run tests and show the browser window (disable headless mode):

php artisan dusk --browse

By default, Laravel Dusk may run Chrome in headless mode, meaning the browser actions happen in the background and are not visible. Using the --browse option opens a visible Chrome window so you can watch Dusk perform each action in real time, such as opening pages, typing into fields, clicking buttons, and submitting forms.

This is especially useful when:

Run one file:

php artisan dusk tests/Browser/StudentFormTest.php

Create test:

php artisan dusk:make LoginTest

More Dusk Actions

Click link:

->clickLink('Home')

Select dropdown:

->select('class', '10')

Check text:

->assertSee('Welcome')

Check URL:

->assertPathIs('/dashboard')

Wait for element:

->waitFor('.success-message')

Take screenshot:

->screenshot('student-form')

Slow Down the Test to Watch Live Browser Actions

Sometimes you may want to visually watch Dusk fill the form step by step for learning or debugging purposes. You can add pause() commands between actions.

Example:

$browser->visit('/student')
        ->pause(1000)

        ->type('name', 'Niel John')
        ->pause(1000)

        ->type('email', 'nielsjohn@test.com')
        ->pause(1000)

        ->type('password', 'Password@123')
        ->pause(1000)

        ->radio('gender', 'Male')
        ->pause(1000)

        ->check('hobbies[]')
        ->pause(1000)

        ->select('class', '10')
        ->pause(1000)

        ->type('dob', '2008-05-15')
        ->pause(1000)

        ->type('address', '123 School Street, Chennai')
        ->pause(1000)

        ->press('Register')
        ->pause(2000)

        ->assertSee('Student Registered Successfully');

The value passed to pause() is in milliseconds:

->pause(1000) // 1 second
->pause(2000) // 2 seconds
->pause(5000) // 5 seconds

This is useful when learning Laravel Dusk because you can see each field being filled in real time inside the Chrome browser. It is also helpful for debugging when a test fails and you want to observe exactly what Dusk is doing.


Easy Summary

Laravel:

Form:

Testing:

Laravel Dusk:

Dusk can:

Think of Dusk as a robot student that uses your website exactly like a real user and reports whether everything works correctly.

Exit mobile version