1
votes

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
Yes this is normal. The file affecting it is phpunit.xmlapokryfos
What do you want to test? imo you should never run tests again async jobs as you are not guarenteed they be executed. But there is solutons to combat that :)mrhn
You should look at Queue::fake() and Event::fake(). This way you can test of a job way dispatched, without actually running the job. Testing does not necessarily require you to run complete flows. Rethink your tests, what do you really want to test?Maarten Veerman
Thanks, but the point of this test is in fact to exercise the complete job submission, queuing, execution and status monitoring endpoints together. With QUEUE_DRIVER set to 'database' in phpunit.xml though, the job now never gets queued (constructor is called, but nothing appears in the jobs table). Ideas?Dan

1 Answers

2
votes

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.