【问题标题】:Not following how to test broadcast events in laravel不遵循如何在 laravel 中测试广播事件
【发布时间】:2020-05-13 07:22:32
【问题描述】:

因此考虑以下事件:

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

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

【问题讨论】:

    标签: laravel laravel-testing laravel-events


    【解决方案1】:

    来自laravel docs

    要调度事件,您可以将事件的实例传递给 事件助手。助手将把事件分派给它的所有 注册听众。由于事件助手是全球可用的, 您可以从应用程序中的任何位置调用它:

    event(new UpdateApprovedClinicianCountBroadcastEvent($count))
    

    并且测试将如下断言它已被分派:

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

    【讨论】:

    • 您不能像现在这样直接调用广播事件,它们必须是伪造的,因为当我这样做时,它试图以物理方式发送广播,但它会因异常而失败。怎么伪造它是行不通的,因为它永远不会被派发。
    猜你喜欢
    • 2020-01-17
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2016-06-12
    • 2017-05-04
    • 2020-04-28
    相关资源
    最近更新 更多