How to Implement Testing for Sending Images in Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents for Laravel articles
I wrote about how to implement testing for sending images in Laravel using PHPUnit.
Environment
Laravel Framework 6.18.41
"phpunit/phpunit": "~8.5",
Using faker
use Illuminate\Http\UploadedFile;
~~~~
public function test_SendImage()
{
$image = UploadedFile::fake()->image('avatar.jpg'); // Create an image using faker
$data = [
'image' => $image
];
$route = 'image.store'; // Name set in routing
$response = $this->post(route($route),$data);
$response->assertStatus(200);
}
How to test with actual images
Faker is convenient and allows you to change the size, making it easy to implement.
However, there may be times when you want to use actual images for testing.
In that case,
use Illuminate\Http\UploadedFile;
~~~~
public function test_SendImage()
{
$image = new UploadedFile(
'./tests/Feature/Data/test.jpg', // Prepare the original file and write the relative path of that file
'test.jpg', // File name
'image/jpeg', //mime
null,
true
);
$data = [
'image' => $image
];
$route = 'image.store'; // Name set in routing
$response = $this->post(route($route),$data);
$response->assertStatus(200);
}
When you can send actual files
This method allows you to handle various mime types with just this, which can be useful.
Files are not just images, so I think it's a good choice as one option.
Summary
That's all.
I hope it can be helpful for someone.
Please contact me via Twitter DM for feedback.
That's all!
Popular Articles