Laravel Dusk is an end-to-end testing tool provided by the Laravel framework that allows developers to write browser tests for their web applications. With Dusk, you can simulate user interactions, perform assertions, and ensure your application functions correctly from a user's perspective. In this post, we'll explore the capabilities of Laravel Dusk and demonstrate how to write end-to-end tests for your web applications.
Setting Up Laravel Dusk
- Installation: Install Laravel Dusk via Composer.
composer require --dev laravel/dusk
Dusk Configuration: Publish the Dusk configuration file.
php artisan dusk:install
Writing Your First Dusk Test
Let's create a simple Dusk test that checks if the login functionality works as expected.
- Generate a Test: Use the
dusk
Artisan command to generate a new test file.
php artisan dusk:make LoginTest
Writing the Test:
// tests/Browser/LoginTest.php
namespace Tests\Browser;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class LoginTest extends DuskTestCase
{
public function testLogin()
{
$this->browse(function (Browser $browser) {
$browser->visit('/login')
->type('email', 'test@example.com')
->type('password', 'password')
->press('Login')
->assertPathIs('/dashboard')
->assertSee('Welcome to your Dashboard!');
});
}
}
Run the Test:
php artisan dusk
Dusk Assertions
Dusk provides a wide range of assertions to verify elements and behavior on web pages.
assertSee
: Check if the given text is present on the page.assertDontSee
: Verify that the given text is not present on the page.assertPathIs
: Ensure the current URL matches the given path.assertVisible
: Check if an element is visible on the page.assertTitle
: Verify the page title.
Interacting with Pages
Dusk allows you to simulate user interactions on web pages.
click
: Click on a link or element.type
: Enter text into an input field.select
: Select an option from a dropdown.attach
: Upload a file.press
: Press a button.
Running Dusk Tests in Headless Mode
Run Dusk tests in headless mode (without a browser window) using ChromeDriver in CI/CD environments.
- Install ChromeDriver:
./vendor/laravel/dusk/bin/chromedriver-linux
Configure Dusk:
// .env
DUSK_DRIVER=chrome
Laravel Dusk provides a powerful and convenient way to write end-to-end tests for your web applications. By simulating user interactions and performing assertions, you can ensure that your application functions correctly from a user's perspective.
With Dusk, you can automate testing tasks and catch potential bugs early in the development process, improving the overall quality and reliability of your web applications.
Embrace Laravel Dusk as a valuable addition to your testing arsenal, and reap the benefits of robust, reliable, and thoroughly tested web applications.