A Laravel Testable Event Listener.

v0.1 2018-12-31 11:54 UTC

This package is auto-updated.

Last update: 2022-01-18 15:49:37 UTC


When developing using TTD pattern, Laravel allow you to fake any event. faking event will prevent the dispatcher from firing that event and so, no listener for this event will be executed. But in some scenarios, we need to fire this event but execute some listener and ignore others, here is why we create this package.

This package allow you to fire an event during testing, but restrict the listener for this event.


You can install the package via composer:

composer require digitalcloud/testable-event-listener

Usage Example

Suppose we have an event fired when we create a new user, and in the normal behavior we have many listener to this event, but during testing we want some of those event to be executed and the other to be ignored.

The user model will fire the \App\Events\UserCreating Event when the Eloquent creating event fired.


namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
    protected $dispatchesEvents = [
        'creating' => \App\Events\UserCreating::class

Our EventServiceProvider look like this:


namespace App\Providers;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
    // ...
    protected $listen = [
        \App\Events\UserCreating::class => [
            // ...
            // ...
    // ...

But when testing we need to run only one listener, \App\Listeners\UserCreating::class, and ignoring all other listener. To do this we can call the EventFaker:fake and pass it the array of fackable event with the required listener to be executed.


namespace Tests\Unit;

use App\User;
use DigitalCloud\TestableEventListener\EventFaker;
use Tests\TestCase;

class ExampleTest extends TestCase
     * A basic test example.
     * @return void
    public function testBasicTest()
            \App\Events\UserCreating::class => [
        $user = factory(User::class)->create();

the result is:

PHPUnit 7.5.1 by Sebastian Bergmann and contributors.


Time: 863 ms, Memory: 14.00MB

OK (1 test, 1 assertion)

Process finished with exit code 0