Courses

Testing in Laravel 11: Advanced Level

Testing Job Dispatching with Bus Fake

Summary of this lesson:
- Use Bus::fake() to test job dispatching
- Assert jobs are dispatched correctly
- Verify job execution without actual processing
- Check job dispatch parameters
- Simulate background job testing

We continue discussing faking in the Laravel tests because, in many cases, we cannot directly replicate the actual scenario.

We cannot replicate the same identical scenario for Jobs that are dispatched into the queue since the queue jobs are executed later.

That's why we need to fake the queue mechanism. In this case, we will fake the Bus to assert that the Job was actually fired and dispatched into the queue.


Scenario Example

Imagine a scenario where you dispatch a Job to notify some users after a new product is created.

use App\Models\Product;
use Illuminate\Http\Request;
use App\Jobs\NewProductNotifyJob;
use Illuminate\Http\RedirectResponse;
 
class ProductController extends Controller
{
// ...
 
public function store(Request $request): RedirectResponse
{
$product = Product::create($request->all());
 
if ($request->hasFile('photo')) {
$filename = $request->file('photo')->getClientOriginalName();
$request->file('photo')->storeAs('products', $filename);
$product->update(['photo' => $filename]);
}
 
NewProductNotifyJob::dispatch($product);
 
return redirect()->route('products.index');
}
 
// ...
}

The Job is straightforward: it only logs an info message.

use App\Models\Product;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
 
class NewProductNotifyJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
public function __construct(private readonly Product $product)
{}
 
public function handle(): void
{
info('Sending notification to everyone about ' . $this->product->name);
}
}

The Test

Now, we need to test that the Job was...

The full lesson is only for Premium Members.
Want to access all 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord