How do you test events in Laravel?

How do you test events in Laravel?

Testing events in Laravel can be done using the built-in testing features that allow you to ensure your event is dispatched correctly. Here’s how to do it in a few simple steps:

1. Fake Events

You can use the Event::fake() method to prevent actual event dispatching and instead focus on asserting whether an event was triggered.

Example

<?php
Event::fake();  // Prevent real event dispatching

// Perform some action that should trigger an event
$user = User::factory()->create();
event(new UserRegistered($user));

// Assert that the event was dispatched
Event::assertDispatched(UserRegistered::class);
?>

2. Fake Specific Events

If you want to fake only specific events, pass them to Event::fake().

Example

<?php
Event::fake([UserRegistered::class]);

// Perform actions
event(new UserRegistered($user));

// Assert that only the specified event was dispatched
Event::assertDispatched(UserRegistered::class);
?>

3. Ensure Event Wasn’t Dispatched

To confirm an event was not dispatched, use assertNotDispatched().

Example

<?php
Event::assertNotDispatched(OrderPlaced::class);
?>

Related Questions & Topics