【问题标题】:How to test/assert if an event is broadcasted in Laravel如果在 Laravel 中广播事件,如何测试/断言
【发布时间】:2020-01-17 14:45:06
【问题描述】:

我正在开发一个 Laravel 应用程序。我在我的应用程序中使用 Laravel 广播。我现在要做的是测试是否在 Laravel 中广播了一个事件。

我正在广播这样的活动:

broadcast(new NewItemCreated($item));

我想测试事件是否被广播。我该如何测试它?我的意思是在单元测试中。我想做类似的事情

Broadcast::assertSent(NewItemCreated::class) 

其他信息

该事件在创建项目时触发的观察者事件中广播。

【问题讨论】:

    标签: laravel laravel-testing laravel-events laravel-broadcast


    【解决方案1】:

    我认为你可以通过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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      我认为您可以将广播或多或少视为事件,因此您可以参考文档的this section

      【讨论】:

        【解决方案3】:

        如果您使用broadcast($event) 广播您的活动,该函数将调用广播工厂的event 方法,您可以像这样模拟:

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

        不确定这是否是实现这一目标的最佳方法,但它是唯一对我有用的方法。

        【讨论】:

          猜你喜欢
          • 2020-05-13
          • 2013-05-21
          • 1970-01-01
          • 2020-04-28
          • 2016-06-12
          • 2017-05-04
          • 2015-10-20
          • 2020-02-11
          相关资源
          最近更新 更多