My intention is to allow developers to generate all Livewire components unit test easily with one single command.
TLDR
Create a new artisan command:
Then copy paste the following:
namespace AppConsoleCommands;
use LivewireComponent as LivewireComponent;
use SymfonyComponentFinderFinder;
use IlluminateConsoleCommand;
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 LivewireLivewire;
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.”);
}
}
}
}
By setting up above class, you can generate Livewire unit test easily – the above class assuming you are:
Using Pest – you can improve if option –phpunit provided, it will use PHP Unit class template instead of Pest template.
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: