I have a package with multiple event listeners that listen to the events emitted by the Laravel queue:
class SetTrackableJobProcessingStatus
{
/**
* Create the event listener.
*/
public function __construct(
public TrackableJobUpdater $updater,
) {}
/**
* Handle the event.
*/
public function handle(JobProcessing $event): void
{
$jobUuid = $event->job->uuid();
if ($this->updater->trackableJobModelExists($jobUuid)) {
$trackableJobModel = $this->updater->retrieveTrackableJobModel($jobUuid);
$this->updater->setProcessingStatus($trackableJobModel);
}
}
}
Which uses these methods in the TrackableJobUpdater
service class:
class TrackableJobUpdater
{
/**
* Set the job status to processing and update the started_at timestamp.
*/
public function setProcessingStatus(TrackableJob $trackableJob): bool
{
return $trackableJob->update([
'status' => Status::Processing,
'started_at' => now(),
]);
}
/**
* Determine if a trackable job model exists for a job using its uuid.
*/
public function trackableJobModelExists(string $uuid): bool
{
return TrackableJob::where('job_uuid', $uuid)->exists();
}
/**
* Retrieve a trackable job model using a job uuid.
*/
public function retrieveTrackableJobModel(string $uuid): TrackableJob
{
return TrackableJob::where('job_uuid', $uuid)->sole();
}
}
How would I go about writing a test case for this, I can test that the listener works (passes):
class SetTrackableJobQueuedStatusTest extends TestCase
{
use RefreshDatabase;
public function test_listens_to_laravel_job_queued_event(): void
{
Event::fake();
Event::assertListening(JobQueued::class, SetTrackableJobQueuedStatus::class);
}
}
I want to also test that the the listener works when a job starts processing. How can I manually dispatch/start a JobProcessing
event in the exact same way Laravel dispatches it? I tried:
public function test_updates_processing_status()
{
$jobProcessingEventListener = new SetTrackableJobProcessingStatus(new TrackableJobUpdater());
$jobProcessingEventListener->handle(new JobProcessing('default', new TrackedSuccessfulJob()));
}
Where TrackedSuccessfulJob
is a normal job class that extends a custom tracking class.
But this gives me the warning:
Expected parameter of type ‘IlluminateContractsQueueJob’ expected
And the error:
Call to undefined method uuid() on
Simply dispatching a job like: TrackedSuccessfulJob::dispatch();
does not dispatch all events. For example, the JobQueued
event is not dispatched.