Inertia.js Events for Laravel Dusk

Overview

Inertia.js Events for Laravel Dusk

Latest Version on Packagist run-tests Total Downloads Buy us a tree

Requirements

  • PHP 7.4+
  • Vue
  • Laravel 8.0 and higher

Support

We proudly support the community by developing Laravel packages and giving them away for free. Keeping track of issues and pull requests takes time, but we're happy to help! If this package saves you time or if you're relying on it professionally, please consider supporting the maintenance and development.

Blogpost

If you want to know more about the background of this package, please read the blogpost: A package for Laravel Dusk to wait for Inertia.js events

Installation

You can install the package via composer:

composer require protonemedia/inertiajs-events-laravel-dusk --dev

Add the inertiaEventsCount object to your main JavaScript file, somewhere above the creation of the Vue application instance.

window.inertiaEventsCount = {
    navigateCount: 0,
    successCount: 0,
    errorCount: 0,
}

In the creation of the Vue application instance, use the mounted method to register the event listeners.

new Vue({
  mounted() {
    Inertia.on('navigate', (event) => {
      window.inertiaEventsCount.navigateCount++;
    })

    Inertia.on('success', (event) => {
      window.inertiaEventsCount.successCount++;
    })

    Inertia.on('error', (event) => {
      window.inertiaEventsCount.errorCount++;
    })
  }
})

Usage

This package provides three helper methods for your Laravel Dusk tests.

Error

The waitForInertiaError() method may be used to wait until the Error event is fired. You can use it to assert against responses where validation errors are returned.

Navigate

The waitForInertiaNavigate() method may be used to wait until the Navigate event is fired. You can use it to assert a user is redirected, for example, after submitting a form.

Success

The waitForInertiaSuccess() method may be used to wait until the Success event is fired. This is great for testing forms that don't redirect after successfully submitting a form.

Example test



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!');
        });
    }
}

Testing

composer test

Changelog

Please see CHANGELOG for more information about what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Other Laravel packages

  • Laravel Analytics Event Tracking: Laravel package to easily send events to Google Analytics.
  • Laravel Blade On Demand: Laravel package to compile Blade templates in memory.
  • Laravel Cross Eloquent Search: Laravel package to search through multiple Eloquent models.
  • Laravel Eloquent Scope as Select: Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.
  • Laravel Eloquent Where Not: This Laravel package allows you to flip/invert an Eloquent scope, or really any query constraint.
  • Laravel FFMpeg: This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem.
  • Laravel Form Components: Blade components to rapidly build forms with Tailwind CSS Custom Forms and Bootstrap 4. Supports validation, model binding, default values, translations, includes default vendor styling and fully customizable!
  • Laravel Paddle: Paddle.com API integration for Laravel with support for webhooks/events.
  • Laravel Verify New Email: This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.
  • Laravel WebDAV: WebDAV driver for Laravel's Filesystem.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Treeware

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

You might also like...
Add eloquent model events fired after a transaction is committed or rolled back

Laravel Transactional Model Events Add transactional events to your eloquent models. Will automatically detect changes in your models within a transac

Public API for the project coding.events. Made in PHP 8.0 with Lumen 8, PHP-FPM, NGINX and MySQL 8.
Public API for the project coding.events. Made in PHP 8.0 with Lumen 8, PHP-FPM, NGINX and MySQL 8.

coding.events API Uma API feita apenas para passar o tempo, montando uma API para o site coding.events. Sinta-se livre para usar esse código como es

The magic of Inertia.js with the simplicity of Blade

Laravel Splade The magic of Inertia.js, with the simplicity of Blade. Support Splade. We proudly support the community by developing Laravel packages

List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.
⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.

What is laravel charts? Charts is a Laravel library used to create Charts using Chartisan. Chartisan does already have a PHP adapter. However, this li

Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster.

Laravel Kickstart What is Laravel Kickstart? Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster. It com

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application.

Laravel Segment Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application. Installation You can install the pac

Laravel Sanctum support for Laravel Lighthouse
Laravel Sanctum support for Laravel Lighthouse

Lighthouse Sanctum Add Laravel Sanctum support to Lighthouse Requirements Installation Usage Login Logout Register Email Verification Forgot Password

Comments
  • Proposal for a method without any special JavaScript code

    Proposal for a method without any special JavaScript code

    Hi! I just wanted to propose a method for this package that does not require any special JavaScript code to work. This method uses the WebDriver's executeAsyncScript function to attach an actual event listener.

    This is the basic function:

    use Facebook\WebDriver\Exception\ScriptTimeoutException;
    use Facebook\WebDriver\Exception\TimeoutException;
    use Laravel\Dusk\Browser;
    
    function (string $name, ?int $seconds = null): Browser {
        /** @var \Laravel\Dusk\Browser $this */
        $seconds = is_null($seconds) ? $this::$waitSeconds : $seconds;
    
        try {
            $this->driver->manage()
                ->timeouts()
                ->setScriptTimeout($seconds);
    
            $this->driver->executeAsyncScript("
                const done = () => arguments[0]();
                document.addEventListener('inertia:{$name}', done, { once: true });
            ");
        } catch (ScriptTimeoutException $e) {
            throw new TimeoutException("Waited {$seconds} seconds for an Inertia '{$name}' event.");
        }
    
        return $this;
    }
    

    I created a mixin class that can be used with Browser::mixin():

    <?php
    
    use Closure;
    use Facebook\WebDriver\Exception\ScriptTimeoutException;
    use Facebook\WebDriver\Exception\TimeoutException;
    use Laravel\Dusk\Browser;
    
    /** @mixin \Laravel\Dusk\Browser */
    class InertiaEventsMixin
    {
        public function waitForInertia(?int $seconds = null): Closure
        {
            return fn (?int $seconds = null) => $this->waitForInertiaEvent('navigate', $seconds);
        }
    
        public function waitForInertiaError(?int $seconds = null): Closure
        {
            return fn (?int $seconds = null) => $this->waitForInertiaEvent('error', $seconds);
        }
    
        public function waitForInertiaFinish(?int $seconds = null): Closure
        {
            return fn (?int $seconds = null) => $this->waitForInertiaEvent('finish', $seconds);
        }
    
        public function waitForInertiaInvalid(?int $seconds = null): Closure
        {
            return fn (?int $seconds = null) => $this->waitForInertiaEvent('invalid', $seconds);
        }
    
        public function waitForInertiaSuccess(): Closure
        {
            return fn (?int $seconds = null) => $this->waitForInertiaEvent('success', $seconds);
        }
    
        public function waitForInertiaEvent(): Closure
        {
            return function (string $name, ?int $seconds = null): Browser {
                /** @var \Laravel\Dusk\Browser $this */
                $seconds = is_null($seconds) ? $this::$waitSeconds : $seconds;
    
                try {
                    $this->driver->manage()
                        ->timeouts()
                        ->setScriptTimeout($seconds);
    
                    $this->driver->executeAsyncScript("
                        const done = () => arguments[0]();
                        document.addEventListener('inertia:{$name}', done, { once: true });
                    ");
                } catch (ScriptTimeoutException $e) {
                    throw new TimeoutException("Waited {$seconds} seconds for an Inertia '{$name}' event.");
                }
    
                return $this;
            };
        }
    }
    

    Then in my testing service provider:

    \Laravel\Dusk\Browser::mixin(new InertiaEventsMixin);
    

    I'd be happy to provide a pull request if you are interested.

    Anyways, thanks for maintaining this package!

    Cheers from Germany, Michael

    opened by michaelhue 3
Releases(1.2.0)
Owner
Protone Media
We are a Dutch software company that develops apps, websites, and cloud platforms. As we're building projects, we gladly contribute to OSS by sharing our work.
Protone Media
A thin and light scaffolded Laravel Dusk environment.

Laravel Husk Larvel Husk is a thin and light scaffolded Laravel Dusk environment. It allows you to test your JavaScript applications with PHP using Pe

Steve Bauman 85 Dec 26, 2022
Persistent Fakes for Laravel Dusk

Laravel Dusk Fakes Support this package! ❤️ We proudly support the community by developing Laravel packages and giving them away for free. If this pac

Protone Media 3 Sep 5, 2022
Laravel Real-time chat app demo with React, Laravel Echo, Breeze, Socket.io, Redis, Inertia.js, TailwindCSS stack.

Laravel Real-time Chat App You can build yours from scratch with the following Medium article https://medium.com/@sinan.bekar/build-a-real-time-chat-a

Sinan Bekar 9 Oct 3, 2022
Simple SSR Head for Inertia.js Laravel

Inertia.js Laravel SSR Head Simple SSR Head for Inertia Laravel, solve the social media metadata display of small Inertia.js x Laravel site. NOT a ful

Lucas Yang 12 Nov 14, 2022
Laravel Livewire component to show Events in a good looking monthly calendar

Livewire Calendar This package allows you to build a Livewire monthly calendar grid to show events for each day. Events can be loaded from within the

Andrés Santibáñez 680 Jan 4, 2023
Pronto Fuel is a heavilly opnionated starter kit for Laravel and Inertia.js powered by Vite

Pronto Fuel Pronto Fuel is a heavilly opnionated starter kit for Laravel and Inertia.js powered by Vite. It ships with autoimporting features and leve

null 87 Dec 28, 2022
A package that adds view-composer like feature to Inertia.js Laravel adapter

Kinetic A package that adds view-composer like feature to Inertia.js Laravel adapter. Use to be able to share props based on the Inertia component nam

Marvin Quezon 76 Dec 12, 2022
Simple laravel hook for adding meta tags to head for inertia

laravel seo hook for js frameworks simple hook for adding meta tags to <head></head> for js frameworks inertia:react,vue, etc... in app/Meta.php put M

Razmik Ayvazyan 2 Aug 23, 2022
Add The Events Calendar support to Sage 10.

The Events Calendar support for Sage 10 Add The Events Calendar support to Sage 10. For the time being there can only be a blade view, the default-tem

Supermundano 10 Nov 5, 2022
🔥 Fire events on attribute changes of your Eloquent model

class Order extends Model { protected $dispatchesEvents = [ 'status:shipped' => OrderShipped::class, 'note:*' => OrderNoteChanged:

Jan-Paul Kleemans 252 Dec 7, 2022