2

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?

4
  • Yes this is normal. The file affecting it is phpunit.xml
    – apokryfos
    Apr 16, 2021 at 8:19
  • 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
    Apr 16, 2021 at 8:39
  • 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? Apr 16, 2021 at 18:19
  • 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
    Apr 17, 2021 at 18:49

1 Answer 1

3

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.

2
  • Thanks - I knew it would be something embarassingly obvious. However, replacing the value with "database" (same as std .env) results in no job being created or executed. (the constructor is called, but nothing appears in the jobs table nor does handle() ever get called. The point of this test is to exercise the complete job submission, queuing, execution and status monitoring. Any more ideas?
    – Dan
    Apr 17, 2021 at 18:46
  • I'm experiencing the same. My test got through the Job's constructor but didn't execute the handle() method. Did you manage to fix it? Appreciate if you could share your solution too! :) Jul 29, 2021 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.