Fake Timeout Exceptions in Laravel

If you're developing a Laravel app that interacts with external services, it's important to ensure that it can handle timeout exceptions gracefully. Fortunately, testing timeout exceptions in your Laravel app is straightforward using the Laravel HTTP client.

One way to test for timeout exceptions is to use the Http::fake() method in your test. This method allows you to simulate a fake HTTP request and response without actually sending it. You can then make the method throw a new ConnectionException with any message you want.

Here's an example of how to use Http::fake() in your test case:

<?php // ExampleTest.php

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Symfony\Component\HttpFoundation\Response;

test('return service not available response', function () {
    Http::fake(fn() => throw new ConnectionException('Connection timed out'));

    $response = $this->get('/api/jira/search');

    // ... other assertions

In the example above, we're testing whether our app can handle a ConnectionException is thrown by the Http::fake()method. We're expecting the response status to be HTTP_SERVICE_UNAVAILABLE, which means that our app is handling the exception correctly.

By testing for timeout exceptions, you can ensure that your Laravel app is robust and can handle unexpected errors gracefully.