0

所以考虑以下事件:

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

这里没有什么复杂的。

所以根据文档,这就是我想测试这个事件的方式:

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 广播应该发出 [0.360s]

时间:503 毫秒,内存:30.00 MB

有 1 次失败:

1) Tests\Unit\Health\Datasets\Builders\UpdateApprovedClinicianCountBroadcastEventTest::testBroadCastShouldEmit 未调度预期的 [App\Modules\Clinics\Events\UpdateApprovedClinicianCountBroadcastEvent] 事件。断言 false 为 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

那么,如何测试广播事件呢?我应该打电话给这个活动吗?这个调度方法会为我调用它吗?就像我很困惑

4

1 回答 1

0

来自laravel 文档

要调度事件,您可以将事件的实例传递给事件助手。助手会将事件分派给所有已注册的侦听器。由于事件助手是全局可用的,因此您可以从应用程序的任何位置调用它:

event(new UpdateApprovedClinicianCountBroadcastEvent($count))

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

public function testBroadCastShouldEmit() {
    event(new UpdateApprovedClinicianCountBroadcastEvent(1))
    Event::assertDispatched(UpdateApprovedClinicianCountBroadcastEvent::class)
}
于 2020-01-27T22:54:46.597 回答