不了解如何在 laravel 中测试广播事件

Not following how to test broadcast events in laravel

所以考虑以下事件:

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');
    }
}

这里没什么复杂的。

所以根据 the docs 这就是我想测试此事件的方式:

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

    $count = 1;

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

但我得到:

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

那么,您如何测试广播事件? 我应该调用该事件吗?这个调度方法是否为我调用它? 好像我很困惑

来自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))

并且测试如下以断言它已被调度:

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