Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Testing Events and Listeners with Fake

Premium
2 min read

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 of our courses? (31 h 16 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…