0

I found 2 ways of testing whether a job is dispatched or not while doing phpUnit based unit testing in Laravel -

1. $this->expectsJobs(JobClassName::class);

2.

Bus::fake();
Bus::assertDispatched(JobClassName::class);

After scrutinizing Laravel docs, I am not able to figure out which one of the above is a better approach and what is the functional difference between these two approaches.

gauravparmar
  • 884
  • 1
  • 9
  • 23

1 Answers1

3

If you correctly read the documentation, you will see that you can use:

public function test_orders_can_be_shipped()
{
    Queue::fake();

    // Perform order shipping...

    // Assert that no jobs were pushed...
    Queue::assertNothingPushed();

    // Assert a job was pushed to a given queue...
    Queue::assertPushedOn('queue-name', ShipOrder::class);

    // Assert a job was pushed twice...
    Queue::assertPushed(ShipOrder::class, 2);

    // Assert a job was not pushed...
    Queue::assertNotPushed(AnotherJob::class);
}

So do use Queue::fake(); and, after you have run your code, use:

Queue::assertPushed(YourJob::class, 1);

// Or

Queue::assertPushed(function (YourJob $job) use ($variable) {
    return $job->property === $variable;
});
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43