18

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 ?

SuperDJ
  • 7,488
  • 11
  • 40
  • 74
coder fire
  • 993
  • 2
  • 11
  • 24

3 Answers3

62

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.

Bondan Sebastian
  • 974
  • 6
  • 18
14

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);
    }
}
Sumeet
  • 1,683
  • 20
  • 27
1

This my generic method, using a route

Route::get('job-tester/{job}', function ($job) {

    if(env('APP_ENV') == 'local'){

        $j = "\\App\Jobs\\".$job;
        $j::dispatch();

    }
});
Zaid Kajee
  • 712
  • 4
  • 9
  • 22