PHPnews.io

A package for Laravel Dusk to wait for Inertia.js events

Written by Pascal Baljet Media - Blog / Original link on Apr. 8, 2021

Today marks the release of another Laravel + Inertia.js package, this time a small one compared to last week's Tables package. This new package provides helper methods for Laravel Dusk that you can use to wait for specific Inertia.js events to fire. Dusk is a first-party Laravel package that lets you write end-to-end tests. It's jam-packed with assertions and interaction helpers. Luckily, it's effortless to extend Dusk by using macros.

Inertia.js has an event system to hook into lifecycle events. You can, for example, hook into page visits and unsuccessful form requests. The package allows you to wait for events to happen.

Imagine your application has a form to create new users. After successfully storing the user into the database, the application redirects to the "users index" route. When you write a Dusk test for this scenario, you fill in the form, trigger the submit button, and then you want to assert that the user gets redirected to the next page. Now you probably run into an issue where the browser is still handling the store request when you assert that the user is redirected.

This can be solved with the waitForInertiaNavigate() method! You put it between the submit trigger and the following assertion, and everything should be fine. Here's an example of the Dusk test.

<?php

namespace Tests\Browser;

use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\DuskTestCase;

class ExampleTest extends DuskTestCase
{
    use DatabaseMigrations;

    /**
     * A basic browser test example.
     *
     * @return void
     */
    public function it_can_store_a_user_and_redirect_back_to_the_index_route()
    {
        $this->browse(function ($browser) {
            $browser->loginAs(User::first())
                    ->visit(route('user.create'))
                    ->type('name', 'New User')
                    ->press('Submit')
                    ->waitForInertiaNavigate()
                    ->assertRouteIs('user.index')
                    ->assertSee('User Added!');
        });
    }
}

You can find the package at GitHub.

pascalbaljetmedia

« Customizing Stubs in Laravel - Serverless LAMP, Refactoring Legacy Code, and Functional Programming »