Testing Livewire Components in Livewire 3.0

Testing Livewire Components in Livewire 3.0

Step 1: Setting Up Your Testing Environment

Before writing tests, ensure your Laravel application has the necessary testing environment configured:

  1. Database Setup: Use an in-memory SQLite database for testing to keep the tests isolated and fast. Update your phpunit.xml file:


<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>

  1. Install Dependencies: Ensure you have PHPUnit and Laravel’s testing tools installed. Typically, these come pre-installed with Laravel.

  2. Create a Test Class: Use Artisan to generate a test class for your Livewire component:


php artisan make:test LivewireComponentTest --unit

Step 2: Writing Basic Tests

Let’s test a simple Livewire component. For this example, we’ll use a CounterComponent.

CounterComponent.php


<?php

namespace App\Livewire;

use Livewire\Component;

class CounterComponent extends Component
{
    public $count = 0;

    public function increment()
    {
        $this->count++;
    }

    public function decrement()
    {
        $this->count--;
    }

    public function render()
    {
        return view('livewire.counter-component');
    }
}

counter-component.blade.php


<div>
    <h1>Count: {{ $count }}</h1>
    <button wire:click="increment">+</button>
    <button wire:click="decrement">-</button>
</div>

Writing the Test

Open the LivewireComponentTest.php file and write the following test:


<?php

namespace Tests\Unit;

use Tests\TestCase;
use Livewire\Livewire;
use App\Livewire\CounterComponent;

class LivewireComponentTest extends TestCase
{
    /** @test */    public function it_increments_and_decrements_the_counter()
    {
        Livewire::test(CounterComponent::class)
            ->assertSee('Count: 0')
            ->call('increment')
            ->assertSee('Count: 1')
            ->call('decrement')
            ->assertSee('Count: 0');
    }
}

What’s Happening Here?

  1. Livewire::test(): Creates a test instance of the Livewire component.

  2. assertSee(): Ensures the specified text is visible in the rendered output.

  3. call(): Simulates calling a method in the component.

Run the test using PHPUnit:

Step 3: Testing Component Interactions

Livewire tests allow you to simulate user interactions such as clicking buttons, submitting forms, and updating properties.

Example: Testing Form Submission

For a form component that collects a user’s name:

FormComponent.php


<?php

namespace App\Livewire;

use Livewire\Component;

class FormComponent extends Component
{
    public $name;

    public function submit()
    {
        $this->validate([
            'name' => 'required|min:3',
        ]);
    }

    public function render()
    {
        return view('livewire.form-component');
    }
}

form-component.blade.php


<div>
    <form wire:submit.prevent="submit">
        <input type="text" wire:model="name">
        <button type="submit">Submit</button>
    </form>
    @error('name') <span>{{ $message }}</span> @enderror
</div>

Test for FormComponent


/** @test */public function it_validates_the_name_field()
{
    Livewire::test(FormComponent::class)
        ->set('name', '')
        ->call('submit')
        ->assertHasErrors(['name' => 'required']);

    Livewire::test(FormComponent::class)
        ->set('name', 'Jo')
        ->call('submit')
        ->assertHasErrors(['name' => 'min']);

    Livewire::test(FormComponent::class)
        ->set('name', 'John Doe')
        ->call('submit')
        ->assertHasNoErrors();
}

What’s Happening Here?

  1. set(): Sets a property value on the component.

  2. assertHasErrors(): Asserts that the component has validation errors for a specific field.

  3. assertHasNoErrors(): Asserts that there are no validation errors.

Step 4: Testing Browser Events

Livewire components often dispatch browser events. You can test these events to ensure they are triggered as expected.

Example: Testing a Browser Event

For a notification component:

NotificationComponent.php


<?php

namespace App\Livewire;

use Livewire\Component;

class NotificationComponent extends Component
{
    public function triggerNotification()
    {
        $this->dispatch('notification', ['message' => 'Hello World']);
    }

    public function render()
    {
        return view('livewire.notification-component');
    }
}

Test for NotificationComponent


/** @test */public function it_dispatches_a_notification_event()
{
    Livewire::test(NotificationComponent::class)
        ->call('triggerNotification')
        ->assertDispatched('notification', ['message' => 'Hello World']);
}

What’s Happening Here?

  1. assertDispatched(): Ensures that the specified browser event was dispatched with the correct payload.

Final Output

With these tests, you can ensure:

  1. Your Livewire components are functional and reliable.

  2. User interactions and form submissions work as expected.

  3. Browser events are triggered correctly.

Key Features Covered Today

  1. Setting up a testing environment for Livewire components.

  2. Writing basic tests for methods and properties.

  3. Simulating user interactions and validating form submissions.

  4. Testing browser events in Livewire components.

© Copyright 2025 Wontonee. All Right Reserved.

×How can I help you?