Reputation: 14831
I am developing a Laravel application. I am using Laravel Broadcast in my application. What I am trying to do now is that I am trying to test if an event is broadcasted in Laravel.
I am broadcasting an event like this:
broadcast(new NewItemCreated($item));
I want to test if the event is broadcasted. How can I test it? I mean in unit test. I want to do something like
Broadcast::assertSent(NewItemCreated::class)
That event is broadcasted within the observer event that is triggered when an item is created.
Upvotes: 4
Views: 7691
Reputation: 75
If you're broadcasting your event with broadcast($event)
, that function will call the event
method of the Broadcasting Factory, that you can mock, like this:
$this->mock(\Illuminate\Contracts\Broadcasting\Factory::class)
->shouldReceive('event')
->with(NewItemCreated::class)
->once();
// Processing logic here
Not sure if this is the best way to achieve this, but it's the only one that worked for me.
Upvotes: 2
Reputation: 1752
I think you can achieve this with 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);
}
}
Upvotes: 11
Reputation: 3567
I think you can treat broadcasting more or less like events, so you can refer to this section of the documentation.
Upvotes: 4