Laravel Dusk: How to Test SPA Applications in PHP

Introduction

Laravel Dusk is a powerful browser automation tool designed for end-to-end testing of web applications, including Single Page Applications (SPAs). It allows developers to test both the functionality and visual aspects of their applications in a real browser environment. Unlike traditional unit testing, which focuses on individual components, Dusk provides the ability to test the entire application from the user’s perspective.

This guide explores how to set up and use Dusk for testing SPAs in Laravel effectively.

Why Use Laravel Dusk for SPA Testing?

  • Full Browser Testing: Dusk runs tests in a real browser (ChromeDriver).
  • JavaScript Support: Ideal for SPAs where frontend interactions depend heavily on JavaScript.
  • Simplified Setup: No Selenium or third-party drivers needed.
  • Automatic Browser Management: Dusk automatically manages browser instances, including handling headless mode for CI/CD pipelines.
  • Visual Regression Testing: Capable of verifying UI consistency across changes.

Setting Up Laravel Dusk

  1. Install Dusk:

    composer require --dev laravel/dusk
    
  2. Publish Dusk Configuration:

    php artisan dusk:install
    
  3. Run Initial Tests:

    php artisan dusk
    
  4. Configure Environment: Ensure the .env.dusk file is properly set up for your testing database and application URL.


Writing Your First SPA Test

namespace Tests\Browser;

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

class SPATest extends DuskTestCase
{
    public function test_can_navigate_through_spa()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->waitForText('Welcome')
                    ->clickLink('About')
                    ->waitForText('About Page')
                    ->assertSee('About Page');
        });
    }
}

Handling Forms and Modals

public function test_can_submit_form()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('/contact')
                ->type('name', 'John Doe')
                ->type('email', '[email protected]')
                ->press('Submit')
                ->waitForText('Thank you for your message!')
                ->assertSee('Thank you for your message!');
    });
}

Testing Login Forms

public function test_user_can_login()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('/login')
                ->type('email', '[email protected]')
                ->type('password', 'password')
                ->press('Login')
                ->assertPathIs('/dashboard');
    });
}

Running Dusk Tests

php artisan dusk

Running Tests in Headless Mode

php artisan dusk --headless

Running Specific Tests

php artisan dusk --filter=SPATest

Laravel Dusk Tips and Tricks

1. Use the waitFor Method:

$browser->waitFor('#submit');

2. Check Element Visibility:

$browser->assertVisible('#submit');
$browser->assertNotVisible('#submit');

3. Capture Screenshots:

$browser->storeScreenshot('screenshots/test_screenshot.png');

4. Retrieve Field Values:

$value = $browser->value('#email');

5. Test Dropdown and Radio Selection:

$browser->select('my-select', '1');
$browser->radio('my-radio', '2');

6. Simulate Keyboard Actions:

$browser->keys('#input-field', 'Hello World', '{enter}');

7. Resize Browser Window:

$browser->resize(1280, 800);

Best Practices for SPA Testing with Dusk

  • Use Wait Methods: Utilize waitForText, waitForElement for async elements.
  • Keep Tests Independent: Avoid dependencies between tests.
  • Leverage Factories: Use Laravel model factories to generate test data.
  • Use Assertions Wisely: Avoid excessive assertions that can slow down tests.
  • Implement CI/CD Pipelines: Integrate Dusk tests into continuous integration pipelines for automated testing.
  • Capture Screenshots: Use storeScreenshot for visual validation.

Conclusion

Laravel Dusk provides a powerful and straightforward way to test Single Page Applications in PHP. With its real browser testing capabilities and JavaScript support, it is well-suited for modern web applications. Properly configured, Dusk can help catch bugs early and ensure a smooth user experience in production. By leveraging Dusk's full feature set, developers can ensure higher test coverage and better quality assurance for Laravel-based projects.

Recent blogs
Структурные паттерны в программировании

Структурные паттерны в программировании

Порождающие паттерны в программировании

Порождающие паттерны в программировании

Генераторы и итераторы в PHP

Генераторы и итераторы в PHP

Объектно-ориентированное программирование в PHP

Объектно-ориентированное программирование в PHP

Структуры данных в PHP

Структуры данных в PHP