joshbonnick/filament-faker

为Filament表单、块和组件生成伪造的块内容。

v1.1.1 2024-05-09 14:35 UTC

This package is auto-updated.

Last update: 2024-09-08 15:11:14 UTC


README

Filament测试实用库

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Filament Faker是一个用于简化使用Filament资源、表单、块和组件内容的测试的实用库。该库可以帮助您在Filament生态系统中自动生成测试的模拟数据。

功能和用法亮点

  • 数据生成:自动为Filament资源、表单、块和组件生成测试数据。
  • 工厂支持:利用工厂定义进行精确和准确的数据生成。
  • 变异:修改特定组件值以适应您的测试场景。
  • 可配置:使用配置选项来控制数据生成行为。
  • 无缝集成:轻松将库集成到基于Filament的项目中。

内容

要求

  • Filament v3或更高版本。
  • PHP 8.1或更高版本。

安装

您可以通过composer安装此包

composer require joshbonnick/filament-faker --dev

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="filament-faker-config"

用法

在资源上调用fake方法以检索一个填充了伪造数据的字段数组的数组。

<?php

$data = PostResource::fake();
生成的数据示例
[
  "title" => "Hello World",
  "slug" => "hello-world",
  "meta-description" => "Ut voluptas molestiae sint repudiandae sint et quis.",
  "content" => [
    [
      "type" => "App\Filament\Blocks\Heading",
      "data" => [
        "content" => "Impedit ex odio nostrum.",
        "level" => "h5",
      ],
    ],
    [
      "type" => "App\Filament\Blocks\RichEditor",
      "data" => [
        "content" => "<p>Non est molestiae et quia reiciendis et iste.</p>",
      ],
    ],
    [
      "type" => "App\Filament\Blocks\Image",
      "data" => [
        "file" => "https://placehold.co/600x400.png",
        "alt" => "Et nam aut nobis alias possimus voluptatem.",
      ],
    ],
  ],
  "status" => "draft",
  "categories" => [2],
]

测试中的用法

您可以在测试中使用伪造数据。

<?php

namespace Tests\Feature\Filament\Blog;

use App\Enums\PostStatus;
use App\Filament\Resources\Blog\PostResource;
use App\Models\Category;
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\Test;
use Tests\FilamentTestCase;

class PostCreateTest extends FilamentTestCase
{
    use RefreshDatabase;

    #[Test]
    public function it_can_create_posts(): void
    {
        Category::factory()->count(2)->create();

        $data = PostResource::faker()->fake();

        Livewire::test(PostResource\Pages\CreatePost::class)
            ->fillForm($data)
            ->call('create')
            ->assertHasNoFormErrors();

        $this->assertDatabaseHas(Post::class, $data);
    }
}

伪造自定义和插件组件

如果您已添加如Spatie Media Library之类的插件,它添加了SpatieMediaLibraryFileUpload组件,您可以在config/filament-faker.php中注册它,如下所示

<?php

use Filament\Forms\Components\SpatieMediaLibraryFileUpload;

return [
    'fakes' => [
        SpatieMediaLibraryFileUpload::class => fn (SpatieMediaLibraryFileUpload $component) => fake()->imageUrl(),
    ],
];

如果您未注册额外组件,将使用默认的回调,它返回fake()->sentence()的结果。

您也可以通过将它们添加到配置中来自定义内置组件附加的默认伪造方法。

修改生成的数据

如果您需要控制特定组件的值,您可以在伪造构建器上链式调用mutateFake。如果此方法对组件返回null,则它将被忽略并由其他方法填充。

<?php

use Filament\Forms\Components\Field;
use Illuminate\Support\Str;
use App\Services\InjectableService;

$data = PostResource::faker()->mutateFake(function (Field $component, InjectableService $service): mixed {
    return match ($component->getName()) {
        'title' => fake()->jobTitle(),
        default => null,
    };
});

变异方法作为方法

或者,您可以在表单、块或资源中添加一个mutateFake方法。

传递给mutateFake的闭包支持依赖注入,您只需要将\Filament\Forms\Components\Field或特定组件类型(例如\Filament\Forms\Components\TextInput)的类型提示为来获取组件实例。

<?php

namespace App\Filament\Components;

use Filament\Forms\Components\Field;
use Filament\Forms\Components\TextInput;
use App\Services\InjectableService;

class MutatedComponent extends TextInput
{
    public function mutateFake(Field $component, InjectableService $service): string
    {
        return $service->getSomething();
    }
}

禁用来自组件名称的生成

默认情况下,组件名称用于映射到Faker方法以实现更准确的数据。有几种方法可以禁用此行为

use_component_names_for_fake设置为falseconfig/filament-faker.php中,这将默认禁用整个包的行为。

您可以在Faker API上链式调用shouldFakeUsingComponentName以按测试禁用功能。

<?php

$data = PostResource::faker()->shouldFakeUsingComponentName(false)->fake();
// or
$data = PostResource::faker()->getForm()->shouldFakeUsingComponentName(false)->fake();
// or
$data = MyCustomBlock::faker()->shouldFakeUsingComponentName(false)->fake();

使用工厂定义生成数据

如果您需要特定测试的更高精度,则可以启用工厂的使用。当启用工厂使用时,生成数据将使用提供的工厂的定义生成。

如果没有提供工厂,则包将尝试从给定的资源、表单、组件或块中解析一个。

由于该功能在底层执行 Factory::makeOne,我建议仅在测试中使用它,在这些测试中,伪造数据的准确性至关重要。

<?php

namespace Tests\Feature\Services\ContentFormatting;

use App\Contracts\ContentFormatter;
use App\Filament\Resources\PostResource;
use Tests\TestCase;

class FormatBlocksTest extends TestCase
{
    public function test_it_formats_blocks()
    {
        $data = PostResource::faker()->withFactory()->fake();

        $service = app(ContentFormatter::class);
        $content = $service->format($data);
        
        // Make assertions of your formatted content...
    }
}

如果您需要指定一个工厂,可以将 class-stringFactory 的实例传递给 withFactory() 方法。

只有 Resources 可以自动解析工厂,如果您想在 Block 或 Component 中使用工厂,您必须向 withFactory 提供工厂,或者向 ComponentFormBlock 提供模型。

选择定义

如果您只想从工厂中选择特定的定义集,可以将一个 array 作为参数传递给 withFactory() 方法,该数组列出了您想要使用的定义。

$data = PostResource::faker()->withFactory(onlyAttributes: ['title', 'slug'])->fake();

为特定字段生成数据

如果您只需要特定的字段或字段集,您可以使用 Resource 和 Form fakers 上的 onlyFields 方法指定它们。

$data = PostResource::faker()->onlyFields('title', 'slug', 'published_at')->fake();

IDE支持

由于此包使用了 Laravel 的 Macroable 特性,您的 IDE 不会自动找到这些方法。为了解决这个问题,您需要使用 ide-helper 包

变更日志

有关最近更改的更多信息,请参阅 变更日志

鸣谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件