How to test Laravel 5 jobs?

coder fire picture coder fire · Oct 19, 2017 · Viewed 17.2k times · Source

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 ?

Answer

Bondan Sebastian picture Bondan Sebastian · Apr 24, 2018

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.