DEV Community

Cover image for Generate Livewire Unit Test from Created Livewire Components
Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on

2

Generate Livewire Unit Test from Created Livewire Components

My intention is to allow developers to generate all Livewire components unit test easily with one single command.

TLDR

Create a new artisan command:

php artisan make:command CreateLivewireTestCommand
Enter fullscreen mode Exit fullscreen mode

Then copy paste the following:

<?php

namespace App\Console\Commands;

use Livewire\Component as LivewireComponent;
use Symfony\Component\Finder\Finder;
use Illuminate\Console\Command;

class CreateLivewireTestCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'livewire:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Discover Livewire Components and Generate Unit Test';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $paths = [
            app_path('Livewire')
        ];

        foreach ((new Finder())->in($paths)->files() as $file) {
            $component = ucfirst(trim(
                str_replace(
                [realpath(base_path()), '.php']
            ,'', $file->getRealPath()), '/'
            ));
            $className = str_replace('/', '\\', $component);

            if (is_subclass_of($className, LivewireComponent::class)) {

                $directory = base_path(
                    'tests/Feature' . str_replace([app_path(), $file->getFilename()], '', $file->getRealPath())
                );
                $class = $file->getFilenameWithoutExtension();
                $filename = $class . 'Test.php';
                $filepath = $directory . DIRECTORY_SEPARATOR . $filename;

                if(! file_exists($directory)) {
                    mkdir($directory, 0777, true);
                }

                $content = "<?php

        use $className;
        use Livewire\Livewire;

        it('renders successfully', function () {
            Livewire::test($class::class)
                ->assertStatus(200);
        });
        ";

                if(file_exists($filepath)) {
                    unlink($filepath);
                }

                file_put_contents($filepath, $content);

                $this->info("Successfully created $className unit test.");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

By setting up above class, you can generate Livewire unit test easily - the above class assuming you are:

  1. Using Pest - you can improve if option --phpunit provided, it will use PHP Unit class template instead of Pest template.
  2. Willing to overwrite the existing class if any (you can improve the above class by adding --force option - if --force is set, overwrite)

To run the command:

php artisan livewire:test
Enter fullscreen mode Exit fullscreen mode

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay