使用 PHP 單元進行 Laravel 測試 - 檔案測試不支援類型
P粉087074897
P粉087074897 2023-09-14 23:41:39
0
1
575

我正在使用 Laravel 10 和 Livewire 2。我正在為一個元件編寫一個簡單的測試,這只是一個上傳表單。我遇到了一個神秘的訊息錯誤:

FAILED  Tests\Feature\Livewire\UploadAssetTest > book can be saved correctly                                                             
Type is not supported

  at vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php:88
     84▕             default => json_encode($data, $this->encodingOptions),
     85▕         };
     86▕ 
     87▕         if (! $this->hasValidJson(json_last_error())) {
  ➜  88▕             throw new InvalidArgumentException(json_last_error_msg());
     89▕         }
     90▕ 
     91▕         return $this->update();
     92▕     }

測試是:

/** @test */
    public function book_can_be_saved_correctly()
    {
        $admin = User::factory()->create();
        $this->actingAs($admin);

        Storage::fake('private');

        $testBook = UploadedFile::fake()->create('private/books/test_book.pdf');
        $testCover = UploadedFile::fake()->image('private/covers/test_image.png');

        $emptyForm = (new UploadBookService())->buildForm();

        $book = array_merge($emptyForm,[
            'title' => 'Title Test',
            'author' => 'Author Test',
            'description' => 'Description Test',
            'publishedAt' => '2022',
            'cover' => $testCover,
            'book' => $testBook,
        ]);

        $component = Livewire::test(UploadAsset::class)
            ->set('assetMeta', $book)
            ->call('save');

            Storage::assertExists('books/test_book.pdf');
            Storage::assertExists('covers/test_cover.png');
    }

對於我到目前為止所調試的內容,一旦我在測試中調用set(),就會觸發錯誤。 我可以確認該組件在使用時正在工作。

P粉087074897
P粉087074897

全部回覆(1)
P粉684720851

錯誤是您傳遞的值與 json_encode() 函數不相容,我建議如下:

$book = array_merge($emptyForm,[
    'title' => 'Title Test',
    'author' => 'Author Test',
    'description' => 'Description Test',
    'publishedAt' => '2022',
    'coverPath' => 'private/covers/test_image.png',
    'bookPath' => 'private/books/test_book.pdf', 
]);

$component = Livewire::test(UploadAsset::class)
    ->set('assetMeta', $book)
    ->call('save');
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板