BrokeYourBike's avatar

How to test the job with dispatchSync?

I have a job, that dispatched the other job.

class JobA implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	public function handle()
    {
		// some code here

		JobB::dispatch();
	}
}

Before dispatchNow deprecation, I used to test my job like this:

class JobATest extends TestCase
{
    use RefreshDatabase;

	/** @test */
    public function it_will_dispatch_job_b()
    {
		Queue::fake();

		JobA::dispatchNow();
		// assertions related to JobA

		Queue::assertPushed(JobB::class, 1);
	}
}

But if I use the dispatchSync, both jobs will not be executed. Is there a way to use the same approach as before, with new dispatchSync method, or my code is antipattern?

0 likes
1 reply
BrokeYourBike's avatar
BrokeYourBike
OP
Best Answer
Level 1

I have found an answer. We can specify which job to fake with Bus. In this case the test will look like this:

class JobATest extends TestCase
{
    use RefreshDatabase;

	/** @test */
    public function it_will_dispatch_job_b()
    {
		Bus::fake([JobB::class]);

		JobA::dispatchSync();
		// assertions related to JobA

		Bus::assertDispatched(JobB::class, 1);
	}
}
2 likes

Please or to participate in this conversation.