如何在测试中获取使用 Laravel Livewire 上传的文件的哈希名称

How to get the hashed name of a file that was uploaded with Laravel Livewire in the tests

我正在尝试为以下上传图像的 Livewire 组件编写测试:

use Livewire\Component;
use Livewire\WithFileUploads;

class UploadImage extends Component
{
    use WithFileUploads;

    public $image;

    public function save()
    {
        $this->validate([
            'image' => 'image|mimes:jpg,jpeg',
        ]);

        $storedImage = $this->image->store('images'); // returns e.g. "images/PznpCCFUUDjZuZRDEAGpsr7SxV2qIM2dEsZ3l0zO.jpeg"

        // save $storedImage as the name in the images table 
    }
}

下面的测试失败了,因为文件保存到磁盘和数据库时使用的是散列名称,而不是 test.jpg。如何获取 Livewire 为测试中的图像创建的哈希名称?

组件中的$storedImage与测试中的$image->hashName()不一样

/** @test **/
function it_can_upload_an_image() {
    Storage::fake();

    $image = UploadedFile::fake()->image('test.jpeg');

    Livewire::test(UploadImage::class)
        ->set('image', $image)
        ->call('save');

    $this->assertDatabaseHas('images', [
        'name' => "images/{$image->hashName()}",
    ]);

    Storage::assertExists("images/{$image->hashName()}");
}

我在源代码的测试中找到了答案here。解决方法就是这么简单‍♂️

将 public 属性 添加到 $storedImage 的组件,以便可以在测试中访问它。

例如

use Livewire\Component;
use Livewire\WithFileUploads;

class UploadImage extends Component
{
    use WithFileUploads;

    public $image;

    public $storedImage;

    public function save()
    {
        $this->validate([
            'image' => 'image|mimes:jpg,jpeg',
        ]);

        $this->storedImage = $this->image->store('images');

        // save $storedImage as the name in the images table 
    }
}

现在可以从测试中访问散列名称:

/** @test **/
function it_can_upload_an_image() {
    Storage::fake();

    $image = UploadedFile::fake()->image('test.jpeg');

    $storedImage = Livewire::test(UploadImage::class)
        ->set('image', $image)
        ->call('save')
        ->get('storedImage');

    $this->assertDatabaseHas('images', [
        'name' => $storedImage,
    ]);

    Storage::assertExists($storedImage);
}

如果您想获取上传文件的原始名称,您可以使用 getClientOriginalName 方法

所以你可以做到

$this->file->getClientOriginalName()

这对我有用。

$validatedData = $this->validate();
$imageName = $this->image->store('public/events');
$validatedData['image'] = str_replace("public/events/", "", $imageName);