Courses

Testing in Laravel 11: Advanced Level

Testing Events and Listeners with Fake

Summary of this lesson:
- Use Event::fake() for event testing
- Assert event dispatching
- Check event listeners
- Verify event firing
- Test event-driven application behavior

Another non-standard or non-linear thing you can test in Laravel is the Event/Listener pattern.

By now, you should probably have noticed the pattern in how "faking" something in Laravel works:

  • You fake the process
  • You make other arrangements
  • You perform the main "act"
  • You assert the results

So, it is pretty similar with Events and Listeners.


The Example

When you use the Laravel Breeze starter kit, registration fires an Event that the user has registered. Then, someone can add a Listener or multiple Listeners to do something, like notify someone.

app/Http/Controllers/Auth/RegisteredUserController.php:

class RegisteredUserController extends Controller
{
// ...
 
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
 
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
 
event(new Registered($user));
 
Auth::login($user);
 
return redirect(route('dashboard', absolute: false));
}
}

The Test

First, let's write a post...

The full lesson is only for Premium Members.
Want to access all 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord