I have the following code in one of my routes:
return Response::download('cv.pdf');
Any idea how to test this? I've tried to use shouldReceive() but that doesn't seem to work ('shouldReceive() undefined function....').
Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response.
TestCase. php : The TestCase. php file is a bootstrap file for setting up the Laravel environment within our tests. This allows us to use Laravel facades in tests and provides the framework for the testing helpers, which we will look at shortly.
Pest is a Testing Framework with a focus on simplicity. It was carefully crafted to bring the joy of testing to PHP. Get started. Source Code.
$response->assertDownload()
was added in Laravel 8.45.0:
Assert that the response is a "download". Typically, this means the invoked route that returned the response returned a Response::download response, BinaryFileResponse, or Storage::download response:
$response->assertDownload();
Learn More:
https://laravel.com/docs/8.x/http-tests#assert-download
EDIT: As pointed by @DavidBarker in his comment to the OP question
The Illuminate\Support\Facades\Response class doesn't actually extend Illuminate\Support\Facades\Facade so doesnt have the shouldRecieve() method. You need to test the response of this route after calling it in a test.
So if you want to test your download functionality, you can try checking the response for errors with:
$this->assertTrue(preg_match('/(error|notice)/i', $response) === false);
You can assert that the status code is 200
$this->assertEquals($response->getStatusCode(), 200);
because sometimes you might have some data returned that match "error" or "notice" and that would be misleading.
I additionally assert that there's an attachment
in the response headers:
$this->assertContains('attachment', (string)$response);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With