philbenoit's avatar

How to test ajax file uploads

I am trying to test my file upload code. The Uploaded file object is not getting sent through to my controller, hoping another pair of eyes might spot the error. Here is my code .

public function testBulkFileCanBeUploaded()
    {

        $user = User::find(1);

        $root = realpath($_SERVER["DOCUMENT_ROOT"]);

        $path          = "$root/tests/files/locations-test.csv";
        $original_name = 'locations-test.csv';
        $mime_type     = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        $size          = 2476;

        $file = new UploadedFile($path, $original_name, $mime_type, $size, null, true);

        $this->actingAs($user)
            ->json('POST', '/api/v1/locations/bulk', ['excel' => $file], ['Accept' => 'application/json'])
            ->seeInDatabase('locations',
                ['name' => 'Phils Test', 'city' => 'Cape Town']);

    }
0 likes
1 reply
philbenoit's avatar
philbenoit
OP
Best Answer
Level 4

For anyone coming across this here is a working version


$root = realpath($_SERVER["DOCUMENT_ROOT"]);

        $path = "$root/tests/files/locations-test.csv";
        $original_name = 'locations-test.csv';

        $file = new UploadedFile($path, $original_name, filesize($path), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', null, true);

        $user = User::find(1);

        $this->actingAs($user)
            ->withSession(['using_company' => 1, 'using_company_name' => 'KiwiDC'])
            ->call('POST', '/api/v1/locations/bulk', [], [], ['excel' => $file], ['Accept' => 'application/json']);

        $this->seeInDatabase('locations',
            ['name' => 'Phils Test', 'city' => 'Cape Town', 'company_id' => 1]);

        $this->assertResponseOk();

Please or to participate in this conversation.