Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Missing Livewire Assertions Laravel Package

christophrumpel/missing-livewire-assertions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev christophrumpel/missing-livewire-assertions
    

    Add the service provider to config/app.php under providers:

    ChristophRumpel\MissingLivewireAssertions\MissingLivewireAssertionsServiceProvider::class,
    
  2. First Use Case: Test a Livewire component's emitted events:

    use function ChristophRumpel\MissingLivewireAssertions\assertEmitted;
    
    $this->livewire(YourComponent::class)
        ->assertEmitted('event-name'); // Checks if the event was emitted
    

Where to Look First

  • Documentation: The blog post explains the motivation and use cases.
  • Assertions List: Check the README for all available assertions (e.g., assertEmitted, assertNotEmitted, assertHasErrors, assertHasNoErrors, etc.).
  • Test Examples: Browse the tests directory for practical usage patterns.

Implementation Patterns

Common Workflows

  1. Testing Event Emissions:

    $this->livewire(YourComponent::class)
        ->call('triggerEvent')
        ->assertEmitted('custom-event')
        ->assertEmitted('custom-event', ['param1', 'param2']); // With payload
    
  2. Validating Form State:

    $this->livewire(YourFormComponent::class)
        ->fill('email', 'invalid-email')
        ->press('submit')
        ->assertHasErrors(['email' => 'required|email']);
    
  3. Asserting UI State:

    $this->livewire(YourComponent::class)
        ->assertSee('Expected Text')
        ->assertDontSee('Unexpected Text')
        ->assertDisabled('submit-button');
    
  4. Testing Component Interactions:

    $this->livewire(ParentComponent::class)
        ->assertChildComponent(ChildComponent::class)
        ->assertChildComponentCount(ChildComponent::class, 2);
    
  5. Mocking External Dependencies: Use assertions to verify interactions with external services (e.g., API calls) via emitted events or error states.

Integration Tips

  • Combine with Laravel Test Helpers: Pair with Laravel’s built-in assertions (e.g., assertDatabaseHas) for end-to-end testing:

    $this->livewire(YourComponent::class)
         ->call('save')
         ->assertEmitted('saved')
         ->assertDatabaseHas('posts', ['title' => 'Test Post']);
    
  • Custom Assertions: Extend the package by creating custom assertions in your test classes:

    use function ChristophRumpel\MissingLivewireAssertions\assertEmitted;
    
    function assertCustomEventEmitted($component, $event, $payload = null) {
        $component->assertEmitted($event, $payload);
        // Add additional logic
    }
    
  • Livewire Test Traits: Use the package alongside Livewire\Testing\TestableLivewire for seamless integration:

    use Livewire\Testing\TestableLivewire;
    use ChristophRumpel\MissingLivewireAssertions\MissingLivewireAssertions;
    
    class YourTest extends TestCase {
        use TestableLivewire, MissingLivewireAssertions;
    }
    
  • Testing Real-Time Updates: Verify real-time updates (e.g., wire:model.live) by asserting emitted events or UI changes:

    $this->livewire(RealTimeComponent::class)
         ->assertSee('Initial Value')
         ->call('updateValue')
         ->assertSee('Updated Value');
    

Gotchas and Tips

Pitfalls

  1. Event Scope:

    • Emitted events are scoped to the test instance. If your component emits events asynchronously (e.g., via dispatchBrowserEvent), ensure the test waits for them:
      $this->livewire(YourComponent::class)
          ->call('asyncAction')
          ->waitForEvent('event-name'); // If using Pest
      
    • For PHPUnit, use sleep() or custom assertions with timeouts (not ideal, but works for simple cases).
  2. Component Lifecycle:

    • Assertions like assertHasErrors or assertHasNoErrors must be called after interactions (e.g., fill or press). Calling them prematurely may fail:
      // ❌ Fails (errors not yet processed)
      $this->livewire(YourComponent::class)
          ->assertHasNoErrors();
      
      // ✅ Works
      $this->livewire(YourComponent::class)
          ->fill('email', 'invalid')
          ->press('submit')
          ->assertHasErrors();
      
  3. Child Component Assertions:

    • assertChildComponent requires the exact class name (including namespace). Use get_class() in your component if unsure:
      $this->livewire(ParentComponent::class)
          ->assertChildComponent(\App\Http\Livewire\ChildComponent::class);
      
  4. Flaky Tests:

    • Livewire’s reactivity can cause flakiness in tests. Use refresh() to reset the component state if needed:
      $this->livewire(YourComponent::class)
          ->call('action')
          ->refresh()
          ->assertEmitted('reset');
      

Debugging Tips

  1. Log Emitted Events: Temporarily log events in your component to debug:

    protected $listeners = ['event-name' => 'handleEvent'];
    
    public function handleEvent($payload) {
        \Log::info('Event received:', $payload);
    }
    
  2. Inspect Component State: Use dump() or dd() in your test to inspect the component’s properties:

    $this->livewire(YourComponent::class)
        ->call('action')
        ->assertEmitted('event')
        ->dump(); // Inspect component state
    
  3. Verify Test Environment: Ensure your test environment matches production (e.g., same Livewire version). Run:

    composer show livewire/livewire
    

    And compare with your composer.json.

Config Quirks

  • No Configuration Needed: The package is zero-config. Install and use assertions directly in tests.

  • Custom Assertion Namespaces: If you encounter naming conflicts, alias the assertions in your test class:

    use function ChristophRumpel\MissingLivewireAssertions\assertEmitted as assertCustomEmitted;
    

Extension Points

  1. Add Custom Assertions: Extend the package by publishing your own assertions. Fork the repository or create a wrapper:

    // app/Testing/Assertions.php
    function assertCustomAssertion($component, $condition) {
        // Custom logic
        assert(true, "Custom assertion passed");
    }
    
  2. Mock Event Dispatching: For isolated testing, mock the dispatchBrowserEvent method in your component:

    $component = $this->livewire(YourComponent::class);
    $component->shouldReceive('dispatchBrowserEvent')->once();
    
  3. Integration with Testing Frameworks:

    • Pest: Use expect() for fluent assertions:
      expect($this->livewire(YourComponent::class))
          ->toHaveEmitted('event-name');
      
    • PHPUnit: Combine with assertTrue() or custom matchers:
      $this->assertTrue(
          $this->livewire(YourComponent::class)->assertEmitted('event-name')
      );
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle