Testing Livewire Components in a Package

Last updated 11/12/2020

This week, me and my colleague worked out how to run Livewire tests on publishable components in a package. Here's how...

This week my collegue and I met an interesting challenge. We were building a Laravel package that has a set of Livewire components we wanted to write tests for. Tricky thing is that these Livewire components weren't designed to stay in the application; they were designed to be published to the parent project. So, when writing a test, the whole thing would blow up because Livewire couldn't find our classes or views.

The Solution

The solution to this problem requires two small steps. Prepare to have your mind blown.

Tell your tests where to find your views

In case you didn't know, Laravel has a views config file that allows you to edit a whole manner of things. In a package using Orchestra\Testbench, we can tap into the config and override it with our own values. So, in your package's base test class, you can add the following:

protected function getEnvironmentSetUp($app)
{
    $app['config']->set('view.paths', [__DIR__ . '/../resources/views']);
}

We basically tell the Illuminate framework that our views aren't located in the traditional resources/views directory, but rather a local package directory. Don't worry, this won't change anything in the real application; this will only happen inside your package tests.

Of course, if your package views are located elsewhere, you'd point them to the correct directory in your package.

Create a fake namespace in you composer.json

The second problem you'll bump into is that your Livewire components aren't in the classic location: App\Http\Livewire. But, with a little edit to your composer.json file, you can change that. You've heard of autoload, right? Well, there's also an autoload-dev option you can use. Any namespaces registered here will be loaded in our package tests but not in the application our package is installed in.

This means we can add the following to our package composer.json file:

"autoload-dev": {
    "psr-4": {
        "Lukeraymonddowning\\MyProject\\Tests\\": "tests",
        "App\\Http\\Livewire": "src/stubs/Livewire"
    }
}

And with that, we're off to the races! Now, in your package tests, Livewire will think that its sat inside a good 'ol Laravel application. You can write your tests and use assertions like $component->assertSee('Hello World!'), and it all just works.

Conclusion

If you want more information on this or are having trouble getting it working in your application, reach out to me on Twitter: @LukeDowning19. I'm always happy to chat tech!

Happy coding!