DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

1

How I can test that one Laravel job dispatches an another one on testing?

Can you help me on how I can assert that a job actually dispatches an another one?

I have the following Laravel Worker:

namespace App\Jobs;

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

use App\Lobs\AnotherJob;

class MyWorker implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;

    public function handle(): void
    {
       AnotherJob::dispatch();
    }
}

And I want to unit-test that my job dispatches the AnotherJob:

namespace

Top comments (1)

Collapse
 
martyhimmel profile image
Martin Himmel

Posted this answer on StackOverflow, too, but here it is for discussion. 😄 Laravel has queue mocks/fakes that will handle that. Try this:

namespace Tests;

use Illuminate\Foundation\Testing\TestCase;
use Illuminate\Support\Facades\Queue;
use App\Jobs\MyWorker;
use App\Jobs\AnotherJob;

class TestMyWorker extends TestCase
{
  public function testDispachesAnotherJob()
  {
    Queue::fake();
    MyWorker::dispatchNow();
    Queue::assertPushed(MyWorker::class);
    Queue::assertPushed(AnotherJob::class);
  }
}

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more