I would like to upload a CSV file via a Laravel API then test the upload with PHPUnit.
What would my store()
function in the Controller and testCreate()
function basically look like.
This is what I got so far:
<?php
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class ProspectListControllerTest extends TestCase
{
use WithoutMiddleware, DatabaseTransactions;
public function testCreate()
{
$file = new Symfony\Component\HttpFoundation\File\UploadedFile(storage_path('/crm/data/test-file.csv'), 'test-file.csv', 'text/plain', 446, null, true);
$this->call('POST', '/api/lists-imports/', [], [], ['csv_file' => $file]);
$this->dump()->assertResponseOk();
}
}
and the controller method looks like:
<?php
namespace App\Http\Controllers;
use App\ListImport;
use Illuminate\Http\Request;
class ListImportController extends Controller
{
public $model = ListImport::class;
public function store(Request $request, ListImport $importList)
{
$request->file('importFile')->move(public_path('storage.crm.data'), $request->file('importFile')->getClientOriginalName());
$importList->importFile = public_path('storage.crm.data') . '/' . $request->file('importFile')->getClientOriginalName();
$importList->save();
}
}
Any help will be appreciated :)
Here's an example of my feature test Laravel 6 and higher ('uploads' is my storage driver):
use Illuminate\Http\UploadedFile;
Storage::fake('uploads');
$header = 'Header 1,Header 2,Header 3';
$row1 = 'value 1,value 2,value 3';
$row2 = 'value 1,value 2,value 3';
$content = implode("\n", [$header, $row1, $row2]);
$inputs = [
'csv_file' =>
UploadedFile::
fake()->
createWithContent(
'test.csv',
$content
)
];
$response = $this->postJson(
'file-upload',
$inputs
);
$response->assertOk();
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