Running Laravel tests with PHPUnit, queued jobs seem to always run in sync mode. How to dispatch them in standard mode?

Viewed 1996

Running Laravel 7 with the job queue using the 'database' driver.

There is a call from the frontend to an API that dispatches a job and immediately returns a response with the status (queued). This works fine when called from the frontend Javascript.

Trying to test this same endpoint with PHPUnit, with a test that calls the same API endpoint, I see that the job appears to be dispatched in sync mode, i.e. the HTTP response does not arrive until the job has completed, because the ->dispatch() method does not return until then.

Both tests are using exactly the same dev environment - one runs async, the other sync.

Can't see anything in the docs about this. How to make the job get queued asynchronously when running with PHPUnit, so we can test the intended behavior?

1 Answers

You can always override .env configurations in the phpunit.xml file.

<server name="QUEUE_CONNECTION" value="a_different_connection"/>

I personally prefer to use the sync connection in my test suite, to make sure everything works correctly.

You can also use Queue::fake(), which is mentioned in the above comment.

Related