Loading...

Testing dynamic file uploads with Laravel

David Carr

1 min read - 18th Mar, 2022

Laravel Laravel-livewire Testing

Table of Contents

When working with file uploads where the file name is generated, how do you know what the file name is and then test if it exists in a test.

First in a controller doing a file upload with a store call which will store the file into a files folder in the public disk, if you don't need to specify the desk leave off the second param.

$path = $request->file('name')->store( 'files', 'public' );

when no disk is required

$path = $request->file('name')->store('files');

Now, this method would return the $path as its return.

Then In a test use the storage fake which tells Laravel to fake a file upload

Storage::fake('files');

To fake an upload you can use:

UploadedFile::fake()->image('avatar.jpg')

To assert the file exists you can check the file in storage:

Storage::assertExists('files/avator.jpg');

But if the file is stored dynamically you won't know the file name in which case you will need to look inside the response from the test. The response is not JSON but a test response. In order to convert this to json use decodeResponseJson on the response. Then you can use json as normal.

Putting it all together

test('can upload file', function () {

Storage::fake('files');

$response = post('api/v1/file', [ 'name' => UploadedFile::fake()->image('avatar.jpg'), ]) ->assertStatus(201) ->assertSessionHasNoErrors();

$path = $response->decodeResponseJson()['data']['path'];

Storage::assertExists($path); });
0 comments
Add a comment