How to test TestJob::dispatchNow in Laravel?

Janez Cergolj • July 2, 2021

Some time ago, I needed to write a test for Laravel job and I've spent hours searching for solution. Testing Laravel jobs that are queued is straightforward.

But how do you test jobs that are 'dispatchedNow'?

The solution is expectsJobs method.

Let's see it in action.

// routes/web.php
Route::get('/job', function() {
    TestJob::dispatchNow();
});


// tests/Feature/JobTest.php
<?php

namespace Tests\Feature;

use App\Jobs\TestJob;
use Tests\TestCase;

class JobTest extends TestCase
{
    /** @test */
    function test_job_is_dispatched()
    {

        $this->expectsJobs(TestJob::class);

        $response = $this->get('job');

    }
}


// app/Jobs/TestJob.php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class TestJob implements ShouldQueue
{
    use Dispatchable;


    public function handle()
    {
        info('Dispatched');
    }
}

And that's it. Very nice, very simple.