FilamentF
Filament12mo ago
Tom

#fileupload #test #pest

I have this FileUpload field:
Forms\Components\FileUpload::make('image')
                            ->image()
                            ->directory('images')


and this test:
it('can replace an image', function () {
    // Configure
    Storage::fake('test');
    FileUpload::configureUsing(function (FileUpload $component) {
        $component
            ->preserveFilenames()
            ->disk('test');
    });

    // Initial
    $filename = fake()->word().'.jpg';
    $file = UploadedFile::fake()->image($filename)->storeAs('images', $filename, ['disk' => 'test']);

    $recipe = Recipe::factory()->create(['image' => $file]);

    expect($recipe->image)->toBe('images/'.$filename);

    // Change
    $newFilename = fake()->word.'-NEW.jpg';
    $newFile = UploadedFile::fake()->image($newFilename);

    livewire(EditRecipe::class, ['record' => $recipe->getRouteKey()])
        ->fillForm([
            'title' => $recipe->title,
            'description' => $recipe->description,
            'image' => [$newFile],
        ])
        ->call('save')
        ->assertHasNoFormErrors();

    $recipe->refresh();

    // Assert
    assertDatabaseHas(Recipe::class, [
        'id' => $recipe->id,
        'image' => 'images/'.$newFilename,
    ]);

    Storage::disk('test')->assertExists('images/'.$newFilename);
    Storage::disk('test')->assertMissing('images/'.$filename);
});


However, the test fails as the model retains the old filename. Has anyone solved this before?
Solution
So with a little assistance from Copilot, I was able to get it working using the ->set() method.
    livewire(EditRecipe::class, ['record' => $recipe->getRouteKey()])
        ->fillForm([
            'title' => $recipe->title,
            'description' => $recipe->description,
            // 'image' => [$newFile],
        ])
        ->set('data.image', [$newFile])
        ->call('save')
        ->assertHasNoFormErrors();
Was this page helpful?