JobQueued event not being fired in test Laravel 11

46 Views Asked by At

I have a listener that should execute when a job gets created/dispatched. This is part of a package. The package has an EventServiceProvider which is registered in the main ServiceProvider of the package.

// src/Listeners/CreateJobTrackingRecord.php

class CreateJobTrackingRecord
{
    /**
     * Handle the given event.
     */
    public function handle(JobQueued $event)
    {
        // ... code to create a database record
        dd('Response from listener.'); // debug
    }
}
// src/Providers/EventServiceProvider.php

protected $listen = [
    JobQueued::class => [
        CreateJobTrackingRecord::class
    ],
];
// src/PackageServiceProvider.php

public function register(): void
{
    $this->app->register(EventServiceProvider::class);
}

I installed the package in a Laravel application. When I run php artisan event:list:

Illuminate\Queue\Events\JobQueued
-> Vendor\Package\Listeners\CreateJobTrackingRecord

The listener is hooked up to the correct event. When I dispatch a job using tinker:

\Bus::dispatch(new App\Jobs\TestJob);
"Response from listener." // ...\src\Listeners\CreateJobTrackingRecord.php

Among other functionalities, I want to test this behaviour in a testcase.

public function test_event_fires_when_job_is_queued(): void
{
    TestJob::dispatch();

    // ... assert record is in database.
}

The table is always empty. Meanwhile, when I dispatch the job using tinker, it works and creates the record.

I've tried to check whether the JobQueueing and JobQueued events are being fired:

public function test_event_fires_when_job_is_queued(): void
{
    Queue::fake(); // tried with and without this

    Event::fakeExcept([
        JobQueued::class,
        JobQueueing::class,
    ]);

    TestJob::dispatch();

    Event::assertDispatched(JobQueueing::class); // tried both separately also
    Event::assertDispatched(JobQueued::class);
}

Results in:

The expected [Illuminate\Queue\Events\JobQueueing] event was not dispatched.

The expected [Illuminate\Queue\Events\JobQueued] event was not dispatched.

Why does this work in an actual application, but not a test?

Also interesting, this test passes:

public function test_listener_listens_to_job_queued_event(): void
{
    Event::fake();

    Event::assertListening(
        JobQueued::class,
        CreateJobTrackingRecord::class
    );
}
0

There are 0 best solutions below