Reputation: 61
I'm writing unit tests for a job's login functionality in Laravel. However, when I attempted to dispatch the job using Job::dispatchSync
, it seems that the job wasn't executed.
Upon further investigation, I found that dispatchSync
dispatches the job on a sync
queue. I'm unsure why it's implemented this way, but I need a method to dispatch the job manually within my unit tests.
Unfortunately, I can't use dispatchNow
on the job because it's unavailable in the Dispatchable
trait. I could manually call the handle
function on the job class, but I'd not resort to this method instead.
Are there any alternative ways to test the logic within job classes? I am using a job structured as:
class ProcessWebhook implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct(private $payload)
{
\Illuminate\Support\Facades\Log::info("job constructor");
}
/**
* Execute the job.
*/
public function handle(Service $service)
{
\Illuminate\Support\Facades\Log::info("job is handled");
}
}
and to test this job I am writing unit tests as
public function test_job($payload): void
{
ProcessWebhook::dispatchSync($client, $payload);
// make assertions
}
According to this code snippet, in Logs, I am getting the constructor message but not the handled message. While using dispatchSync, the job is not called at all by the' handle' method. Using:
(new ProcessWebhook($payload))->handle(app(Service::class));
works fine.
Upvotes: 0
Views: 145