Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shaungbhone's avatar

Pesting form builder with upload file

I am trying to test upload the file in my order. That gives me an error foreach() argument must be of type array|object, string given. Here is my code.

Forms\Components\FileUpload::make('screenshot')
    ->required()
    ->label(__('Screenshot'))
    ->directory('transaction-images')
    ->columnSpanFull(),
test('user can order the product', function () {
    $this->actingAs(User::factory()->create());

    $file = Illuminate\Http\UploadedFile::fake()->create('screenshot.jpg');

    livewire('order.create')
        ->fillForm([
            'url' => fake()->url(),
            'screenshot' => $file->name,
        ]);
});
0 likes
1 reply
LaryAI's avatar
Level 58

To test file uploads in your form using Pest and Livewire, you need to ensure that the file is properly handled in the test. The error you're encountering suggests that the screenshot field is being treated as a string rather than an uploaded file object.

Here's how you can modify your test to properly handle the file upload:

  1. Use the attach method to attach the file to the form.
  2. Ensure that the screenshot field is correctly set to the uploaded file object.

Here's the corrected code:

use Illuminate\Http\UploadedFile;
use Livewire\Livewire;
use App\Models\User;

test('user can order the product', function () {
    $this->actingAs(User::factory()->create());

    $file = UploadedFile::fake()->create('screenshot.jpg');

    Livewire::test('order.create')
        ->set('url', fake()->url())
        ->set('screenshot', $file)
        ->call('submit')
        ->assertHasNoErrors();
});

In this code:

  • UploadedFile::fake()->create('screenshot.jpg') creates a fake file for testing.
  • Livewire::test('order.create') initializes the Livewire component for testing.
  • ->set('url', fake()->url()) sets the url field in the form.
  • ->set('screenshot', $file) sets the screenshot field to the uploaded file object.
  • ->call('submit') simulates the form submission.
  • ->assertHasNoErrors() checks that there are no validation errors.

Make sure that your Livewire component (order.create) is correctly handling the file upload in its submit method. For example:

public function submit()
{
    $this->validate([
        'url' => 'required|url',
        'screenshot' => 'required|file|mimes:jpg,jpeg,png',
    ]);

    // Handle the file upload
    $path = $this->screenshot->store('transaction-images');

    // Save the order with the uploaded file path
    Order::create([
        'url' => $this->url,
        'screenshot_path' => $path,
    ]);

    // Additional logic...
}

This ensures that the file is properly validated and stored during the form submission.

Please or to participate in this conversation.