Jobs run in the background, so how do you test that they were dispatched at all? Laravel provides test helpers that let you assert queue behavior without actually running a worker.
Queue::fake() — Was the Job Dispatched?
Call Queue::fake() at the start of a test. From that point, no job is actually pushed to the queue — they are intercepted and recorded, so you can assert against them.
After a user registers, we expect SendRegisteredUserNotification to be dispatched. Let's verify that.
tests/Feature/RegistrationTest.php:
use App\Jobs\SendRegisteredUserNotification;use Illuminate\Support\Facades\Queue; it('dispatches a notification job when a user registers', function () { Queue::fake(); $this->post('/register', [ 'name' => 'John Doe', 'password' => 'password', 'password_confirmation' => 'password', ]); Queue::assertPushed(SendRegisteredUserNotification::class); });
To go further and inspect the job's payload, pass a closure as the second argument. It receives the job instance, so you can check the data it was dispatched with.
Queue::assertPushed(SendRegisteredUserNotification::class, function ($job) { });
The opposite assertion is just as useful. When registration fails validation, no job should be dispatched.
it('does not dispatch a job when registration data is invalid', function () { Queue::fake(); $this->post('/register', ['email' => 'not-an-email']); Queue::assertNotPushed(SendRegisteredUserNotification::class); });
Asserting Queue Name and Dispatch Count
In lesson 14 we dispatched SendRegisteredUserNotification on the priority queue using...