laravellaravel-testinglaravel-events

Not following how to test broadcast events in laravel


So consider the following event:

class UpdateApprovedClinicianCountBroadcastEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets;

    public $count;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(int $count)
    {
        $this->count = $count;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PresenceChannel('approved-clinician-count');
    }
}

Nothing complicated here.

So according the docs this is how I am suppose to test this event:

public function testBroadCastShouldEmit() {
    Event::fake();

    $count = 1;

    Event::assertDispatched(UpdateApprovedClinicianCountBroadcastEvent::class, function ($e) use ($count) {
        $e->count === $count;
    });
}

But I get:

Tests\Unit\Health\Datasets\Builders\UpdateApprovedClinicianCountBroadcastEventTest x broad cast should emit [0.360s]

Time: 503 ms, Memory: 30.00 MB

There was 1 failure:

1) Tests\Unit\Health\Datasets\Builders\UpdateApprovedClinicianCountBroadcastEventTest::testBroadCastShouldEmit The expected [App\Modules\Clinics\Events\UpdateApprovedClinicianCountBroadcastEvent] event was not dispatched. Failed asserting that false is true.

/Users/xxx/Documents/health/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/EventFake.php:62 /Users/xxx/Documents/health/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:261 /Users/xxx/Documents/health/tests/Unit/Modules/Clinics/Events/UpdateApprovedClinicianCountBroadcastEventTest.php:31

So, how do you test broadcast events? Am I suppose to call the event? Does this dispatch method call it for me? Like I am confused.


Solution

  • From the laravel docs:

    To dispatch an event, you may pass an instance of the event to the event helper. The helper will dispatch the event to all of its registered listeners. Since the event helper is globally available, you may call it from anywhere in your application:

    event(new UpdateApprovedClinicianCountBroadcastEvent($count))
    

    And the test would be as follows to assert it was dispatched:

    public function testBroadCastShouldEmit() {
        event(new UpdateApprovedClinicianCountBroadcastEvent(1))
        Event::assertDispatched(UpdateApprovedClinicianCountBroadcastEvent::class)
    }