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.
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);
}
}
I think you can treat broadcasting more or less like events, so you can refer to this section of the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With