trifek's avatar

Test upload in Tests in Laravel

Hi, I make my first test.

I have this code:

class BlogTest extends TestCase
{
    use RefreshDatabase,
        WithFaker;

    public function setUp(): void
    {
        parent::setUp();
        $this->withoutExceptionHandling();
        $this->refreshDatabase();
        $this->blogRepository = app(BlogRepositoryInterface::class);
        $this->seed('DatabaseSeeder');
    }
    public function testBlogListPageIsWorkingCorrectly()
    {
        $response = $this->get(route('blog'));
        $response->assertSeeText('Blog');

        $response->assertStatus(200);
    }

    public function testCreateNewRecordWithImage()
    {
        $blog = $this->blogRepository->create([
            'title' => 'Test blog title',
            'description' => $this->faker->text( 150),
            'keywords' => $this->faker->text( 150),
            'small_content' => $this->faker->text( 150),
            'content' => $this->faker->realText,
            'is_enable' => $this->faker->boolean(50),
            'visibility_date_from' => $this->faker->dateTimeBetween('-3 months', '0 months'),
            'visibility_date_to' => $this->faker->dateTimeBetween('+3 months', '+6 months'),
            'created_at' => $this->faker->dateTimeBetween('-3 months', '+6 months'),
            'event_date' => $this->faker->dateTimeBetween('-3 months', '+6 months'),
        ]);

        $request = Request::path('public/images/test.jpg');
        if ($request->hasFile('file')) {
            $status = $uploadService->uploadMainImage($request, ['jpg', 'jpeg', 'png', 'bmp'], $blog);
            $fileName = json_decode($status, true);

            $thumbService->createMainThumb($fileName['filePath'], 1920, true);
            $thumbService->createCustomSizeThumb($fileName['filePath'], 1920, 920, true);
            $thumbService->createAspectRatioThumbWidth($fileName['filePath'], 1920, 920, true);
            $thumbService->createAspectRatioThumbHeight($fileName['filePath'], 1920, 920, true);
            $thumbService->createUpsizeThumb($fileName['filePath'], 1920, 920, true);
            $thumbService->cropThumb($fileName['filePath'], 500, 800, true);
        };


        $response = $this->get(route('blog'));
        $response->assertSeeText('Test blog title');
    }
}

It's work fine. I have problem in this part of my code:

$request = Request::path('public/images/test.jpg');
        if ($request->hasFile('file')) {
            $status = $uploadService->uploadMainImage($request, ['jpg', 'jpeg', 'png', 'bmp'], $blog);
            $fileName = json_decode($status, true);

            $thumbService->createMainThumb($fileName['filePath'], 1920, true);
            $thumbService->createCustomSizeThumb($fileName['filePath'], 1920, 920, true);
            $thumbService->createAspectRatioThumbWidth($fileName['filePath'], 1920, 920, true);
            $thumbService->createAspectRatioThumbHeight($fileName['filePath'], 1920, 920, true);
            $thumbService->createUpsizeThumb($fileName['filePath'], 1920, 920, true);
            $thumbService->cropThumb($fileName['filePath'], 500, 800, true);
        };

It's return error: Error: Call to a member function hasFile() on string

I have file in path: public/images/test.jpg

When I use this in controller (normally, with upload form - it's work fine).

How can I make it?

0 likes
3 replies
martinbean's avatar

@trifek That’s not how you test file uploads. At all.

Docs: https://laravel.com/docs/9.x/http-tests#testing-file-uploads

You should also probably be doing thumbnail generation in a queued job. You don‘t want users waiting around for a response whilst your server’s crunching a ~4 MB image into various different sizes.

If you’re testing creating a new blog, then test that. Because all you’re doing is calling a repository method, but then a GET route, not a POST route that would actually create the blog post. If you already have a test for your repository class, then mock it:

public function testCreateBlogPostFromWeb(): void
{
    $this->mock(BlogPostRepository::class, function (MockInterface $mock) {
        $mock->shouldReceive('create')->once();
    });

    $response = $this->post('/posts', [
        // Put request data here...
    ]);

    $response->assertSessionHasNoErrors();
    $response->assertRedirect();
}
trifek's avatar

@martinbean Yes, I know. But in my code I haven't CMS to add / edit records. I try learn only test now. I create records from Seeders/factories - and then I want check it'exist, edit and add images. I have only front-page

to this code can I add files:

$response = $this->post('/posts', [
        // Put request data here...
    ]);

??

martinbean's avatar
Level 80

@trifek You don’t write tests to check records have been added by seeders. You create tests to test application business logic.

Please or to participate in this conversation.