eriktobben's avatar

Laravel Event from Livewire not dispatched in test

Hi!

I have a Livewire component that dispatches a Laravel Event from an action. The Listener is implementing ShouldQueue. This is working fine when manually testing, but when testing with PHPunit, the event is not fired.

The test fails with the following error: The expected [App\Events\ProductVideosChanged] event was not dispatched.

Livewire Component:

public function deleteVideo($videoId)
{
        $video = ProductVideo::where('id', $videoId)->first();
        $video->delete();

        $this->refreshVideos();

        event(new ProductVideosChanged($this->product));
}

EventServiceProvider.php

protected $listen = [
         ProductVideosChanged::class => [
            SyncProductVideos::class,
        ],
];

ProductVideoTest.php

/** @test */
public function it_can_delete_product_video()
{
		// ...

        Event::fake();
        Event::assertDispatched(ProductVideosChanged::class);
}

Why is the event not dispatched in the test?

0 likes
2 replies
Braunson's avatar

Based on the code you have included, you are not calling the deleteVideo method in your test thus no event was dispatched.

You want something more like this:

Livewire::test(YourLivewireComponent::class)->call('deleteVideo');

From there you want to check if the event was emitted

See this Livewire doc for examples and more information.

eriktobben's avatar

@braunson Hi! I did not include it in the post, but this is the logic:

Livewire::test(ProductVideo::class, ['product' => $product])
            ->call('deleteVideo', $videos->first()->id);

Please or to participate in this conversation.