The Problem
Usually on tests where jobs are dispatched the Laravel would throw some kind of exceptions. In order to fix that I would add $this->expectsJobs(SampleJob::class);
to the relevant test
And on tests where jobs were not expected to be dispatched, the Laravel would not throw the mentioned
exception.
However, there are some cases, we need to be absolutely sure no job occur. Especially, since Laravel 5.1 there has been instance in which it does not throw the previously mentioned example.
We have to be sure Laravel is not dispatching any Job, or else it would send thousands of invalid emails, as well as spending a lot credits of our account at our email service provider.
In summary, we need an unit test assertion, validating no job is dispatched.
The Solution
Laravel already has an expectsJobs We’ll modify this to feet our need, and insert it to our TestCase.
private function doesntExpectJobs()
{
$mock = Mockery::mock('Illuminate\Bus\Dispatcher[dispatch]', [$this->app]);
$mock->shouldReceive('dispatch')->never();
$this->app->instance('Illuminate\Contracts\Bus\Dispatcher', $mock);
return $this;
}
The Implementation
The source code is located here
And the expected failing and expected passing tests.
Conclusion
This above code snippet is useful for Laravel 5.1 LTS.
On the other hand the latest version of Laravel (5.4+), has already the above implementation.