How to test/assert if an event is broadcasted in Laravel

6.4k Views Asked by At

I am developing a Laravel application. I am using Laravel Broadcast in my application. What I am trying to do now is that I am trying to test if an event is broadcasted in Laravel.

I am broadcasting an event like this:

broadcast(new NewItemCreated($item));

I want to test if the event is broadcasted. How can I test it? I mean in unit test. I want to do something like

Broadcast::assertSent(NewItemCreated::class) 

Additional information

That event is broadcasted within the observer event that is triggered when an item is created.

3

There are 3 best solutions below

0
On BEST ANSWER

I think you can treat broadcasting more or less like events, so you can refer to this section of the documentation.

0
On

If you're broadcasting your event with broadcast($event), that function will call the event method of the Broadcasting Factory, that you can mock, like this:

$this->mock(\Illuminate\Contracts\Broadcasting\Factory::class)
        ->shouldReceive('event')
        ->with(NewItemCreated::class)
        ->once();

// Processing logic here

Not sure if this is the best way to achieve this, but it's the only one that worked for me.

0
On

I think you can achieve this with Mocking in Laravel (Event Fake)

<?php

namespace Tests\Feature;

use App\Events\NewItemCreated;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * Test create item.
     */
    public function testOrderShipping()
    {
        // this is important
        Event::fake();

        // Perform item creation...

        Event::assertDispatched(NewItemCreated::class, function ($e) {
            return $e->name === 'test' ;
        });

        // Assert an event was dispatched twice...
        Event::assertDispatched(NewItemCreated::class, 2);

        // Assert an event was not dispatched...
        Event::assertNotDispatched(NewItemCreated::class);
    }
}