Skip to content

feat: Add documentation to test file uploads #1362

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 13, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions core/file-upload.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,3 +297,48 @@ uploaded cover, you can have a nice illustrated book record!

Voilà! You can now send files to your API, and link them to any other resource
in your app.

## Testing

To test your upload with `ApiTestCase`, you can write a method as below:

```php
<?php
// tests/MediaObjectTest.php

namespace App\Tests;

use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\ApiTestCase;
use App\Entity\MediaObject;
use Hautelook\AliceBundle\PhpUnit\RefreshDatabaseTrait;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class MediaObjectTest extends ApiTestCase
{
use RefreshDatabaseTrait;

public function testCreateAMediaObject(): void
{
$file = new UploadedFile('fixtures/files/image.png', 'image.png');
$client = self::createClient();

$client->request('POST', '/media_objects', [
'headers' => ['Content-Type' => 'multipart/form-data'],
'extra' => [
// If you have additionnal fields in your MediaObject entity, use the parameters
'parameters' => [
'title' => 'My file uploaded',
],
'files' => [
'file' => $file,
],
]
]);
$this->assertResponseIsSuccessful();
$this->assertMatchesResourceItemJsonSchema(MediaObject::class);
$this->assertJsonContains([
'title' => 'My file uploaded',
]);
}
}
```