abodnar's avatar

How to unit test a POST request that has an uploaded file

I'm setting up a route that will take a file upload, do some processing and then return json. However, when I try to unit test, I'm running into some issues with building the testing to see if my code worked.

Unit test:

class uploadTest extends \TestCase
{
    private $uploadedFile = __DIR__ . '/test.png';
    private $user;

    public function setUp()
    {
        $_FILES = [
            'filename' => [
                'name' => $this->uploadedFile,
                'type' => 'image/png',
                'size' => 5093,
                'tmp_name' => $this->uploadedFile,
                'error' => 0
            ]
        ];
    
        parent::setUp();

        $this->user = new User();
        $this->user->setAttribute('name', 'Test');
            $this->user->setAttribute('password', 'dummy');
            $this->user->setAttribute('email', 'test@test.com');
            $this->user->save();
    }

    public function testPost()
    {
        $this->be($this->user);

        //Does not work
        $this->post('/upload',
             [
                'id' => 1,
                //other vars
            ]
        )->seeJson([
            'id' => 1,
            //other vars
        ]);

        //Works, but does not work with seeJson
            $this->call('POST',
                '/upload',
                [
                    'id' => 1
                ],
                [],
                $_FILES,
                []
            )->seeJson([
            'id' => 1,
            //other vars
        ]);
    }
}

When I try to use the above post method, $attachment is null. But if I use the call method, it works, but I can't do the seeJson test.

Controller store method:

public function store(Requests\UploadRequest $request)
{
        $attachment = $request->file('filename');

        $request->user()->upload()->create([
            'filename' => $attachment->getClientOriginalName(),
            'id' => $request->id
        ]);
}

Any thoughts?

0 likes
2 replies
ifpingram's avatar
Level 4

@abodnar that's because call() has no fluent interface (i.e. it does not return $this). Try splitting the request up like so:

        $this->call('POST',
            '/upload',
            [
                'id' => 1
            ],
            [],
            $_FILES,
            []
        );

        $this->seeJson([
            'id' => 1,
            //other vars
        ]);
2 likes

Please or to participate in this conversation.