Reputation: 41
I want to test multiple event listeners that listen for Laravel's built-in queue events (all the events that live in the Illuminate\Queue\Events
namespace. The listeners are part of a package.
Normally, if I want to test the behaviour of an event listener, I would do something like this:
handle
method on the event.public function test_sends_notification_to_newly_created_user(): void
{
$user = User::factory()->create();
$event = new UserCreated($user);
$eventListener = $this->app->make(SendUserCreationNotification::class);
$eventListener->handle($event);
Notification::assertSentTo($user, WelcomeNotification::class);
}
My listener that listens to the JobQueued
event:
public function handle(JobQueued $event): void
{
$jobUuid = $event->payload()['uuid'];
if (property_exists($event->job, 'trackableJob')) {
$this->updater->setQueuedStatus($event->job->trackableJob, $jobUuid);
}
}
When I try to create the JobQueued
event:
public function test_updates_status_to_queued_in_database(): void
{
$event = new JobQueued(...); // I have to manually specify the payload (don't want to do that)
}
I also tried just dispatching a job and running it but the JobQueued
event never fires:
public function test_updates_status_to_queued_in_database(): void
{
app(Dispatcher::class)->dispatch(new TrackedJob());
$this->artisan('queue:work --once');
}
How do I properly create the JobQueued
event, so I can test my listener?
For clarification, the setQueuedStatus()
method on the updater
class. Its purpose is to set the status to queued and attach the uuid, which we can then use to track it during processing.
public function setQueuedStatus(TrackableJob $trackableJob, string $jobUuid): bool
{
$trackableJob->job_uuid = $jobUuid;
return $trackableJob->update([
'queued_at' => now(),
'status' => Status::Queued,
]);
}
The TrackedJob
class is a test job with an empty handle()
method.
Upvotes: 4
Views: 284
Reputation: 15879
This (the Illuminate\Queue\Events\JobProcessing
event) counts as laravel internals. You should not be wasting your time trying to test it.
What you can test however is
Upvotes: 1