Skip to main content

Testing Queues: Queue::fake, Bus::fake, withFakeQueueInteractions

Premium
4 min read

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',
'email' => '[email protected]',
'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) {
return $job->user->email === '[email protected]';
});

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...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (34 h 11 min)

You also get:

58 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.