Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Laravel 5 jobs?

I try to catch an event, when job is completed

Test code:

class MyTest extends TestCase {

   public function testJobsEvents ()
   {
           Queue::after(function (JobProcessed $event) {
               // if ( $job is 'MyJob1' ) then do test
               dump($event->job->payload());
               $event->job->payload()
           });
           $response = $this->post('/api/user', [ 'test' => 'data' ], $this->headers);
           $response->assertSuccessful($response->isOk());

   }

}

method in UserController:

public function userAction (Request $request) {

    MyJob1::dispatch($request->toArray());
    MyJob2::dispatch($request->toArray());
    return response(null, 200);
}

My job:

class Job1 implements ShouldQueue {
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

     public $data = [];

     public function __construct($data)
     {
         $this->data= $data;
     }

      public function handle()
      {
          // Process uploaded
      }
}

I need to check some data after job is complete but I get serialized data from $event->job->payload() in Queue::after And I don't understand how to check job ?

like image 722
coder fire Avatar asked Oct 19 '17 19:10

coder fire


2 Answers

Well, to test the logic inside handle method you just need to instantiate the job class & invoke the handle method.

public function testJobsEvents()
{
       $job = new \App\Jobs\YourJob;
       $job->handle();

       // Assert the side effect of your job...
}

Remember, a job is just a class after all.

like image 177
Bondan Sebastian Avatar answered Nov 13 '22 21:11

Bondan Sebastian


Laravel version ^5 || ^7

Synchronous Dispatching

If you would like to dispatch a job immediately (synchronously), you may use the dispatchNow method. When using this method, the job will not be queued and will be run immediately within the current process:

Job::dispatchNow()

Laravel 8 update

<?php

namespace Tests\Feature;

use App\Jobs\ShipOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Bus;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_orders_can_be_shipped()
    {
        Bus::fake();

        // Perform order shipping...

        // Assert that a job was dispatched...
        Bus::assertDispatched(ShipOrder::class);

        // Assert a job was not dispatched...
        Bus::assertNotDispatched(AnotherJob::class);
    }
}
like image 45
Sumeet Avatar answered Nov 13 '22 21:11

Sumeet