Pest를 사용하여 Laravel Livewire 유효성 검사 규칙 테스트
해충이란 무엇입니까?
이전에 Pest에 대해 들어본 적이 없다면 다음은 Pest website의 설명입니다.
Pest is a Testing Framework with a focus on simplicity. It was carefully crafted to bring the joy of testing to PHP.
표준 PHP 클래스를 작성하는 대신 테스트를 보다 유창하게 설명하기 위해
test()
또는 it()
를 사용하여 보다 읽기 쉬운 방식으로 테스트를 작성할 수 있습니다. 이전에 JavaScript로 테스트를 작성한 적이 있다면 이것은 매우 친숙하게 보일 수 있습니다.Laravel 및 Livewire와 함께 해충 사용
Pest는 PHP Unit 위에 구축된 PHP 테스트 프레임워크이며 특정 프레임워크가 아닙니다. 대신 다양한 도구 및 프레임워크와 함께 사용할 수 있는 다양한 플러그인이 있습니다.
Laravel을 시작하려면 아래 명령을 실행하여 Pest 및 Pest plugin for Laravel 를 설치한 다음 artisan을 사용하여 Laravel 프로젝트를 설정하여 Pest를 사용할 수 있습니다.
composer require pestphp/pest --dev --with-all-dependencies
composer require pestphp/pest-plugin-laravel --dev
php artisan pest:install
Livewire의 경우 Pest plugin for Livewire을 설치해야 합니다.
composer require pestphp/pest-plugin-livewire --dev
그런 다음
./vendor/bin/pest
또는 php artisan test
를 실행하여 테스트를 실행할 수 있습니다.테스트 변환
아래는 원본 기사의 테스트입니다(Testing validation rules in a Livewire component).
<?php
namespace Tests\Feature;
use App\Http\Livewire\ProfileForm;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ProfileValidationTest extends TestCase
{
use RefreshDatabase;
/**
* @test
* @dataProvider validationRules
**/
public function test_validation_rules($field, $value, $rule)
{
$user = User::factory()->create();
$anotherUser = User::factory()->create(['email' => '[email protected]'])
Livewire::actingAs($user)
->test(ProfileForm::class, ['user' => $user])
->set($field, $value)
->call('save')
->assertHasErrors([$field => $rule]);
}
public function validationRules()
{
return [
'name is null' => ['user.name', null, 'required'],
'name is too long' => ['user.name', str_repeat('*', 201), 'max'],
'email is null' => ['user.email', null, 'required'],
'email is invalid' => ['user.email', 'this is not an email', 'email'],
'email is not unique' => ['user.email', '[email protected]', 'unique'],
'bio is null' => ['user.bio', null, 'required'],
'bio is too short' => ['user.bio', str_repeat('*', 8), 'min'],
'bio is too long' => ['user.bio', str_repeat('*', 1001), 'max'],
];
}
}
요약하면 테스트할 필드, 실패할 것으로 예상되는 값 및 유효성 검사 규칙을 수락하는 테스트를 만듭니다. 그런 다음 이 데이터는 데이터 공급자를 사용하여 여러 데이터 세트에 대해 동일한 테스트를 재사용하여 테스트에 전달됩니다.
해충 테스트 작성
가장 먼저 눈에 띄는 점은 PHP 클래스를 만들 필요 없이
Test.php
로 끝나는 PHP 파일만 생성하면 된다는 것입니다.이메일 사용자가 필요하므로 RefreshDatabase 특성을 사용해야 합니다.
<?php
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
다음으로 우리는 Livewire 구성 요소를 테스트하기 위해 Livewire pest 기능을 사용해야 하므로 use 문과 테스트하려는 ProfileForm Livewire 구성 요소에 이를 포함시키겠습니다.
<?php
use App\Http\Livewire\ProfileForm;
use Illuminate\Foundation\Testing\RefreshDatabase;
use function Pest\Livewire\livewire;
uses(RefreshDatabase::class);
이제 테스트 작성을 시작할 수 있습니다. 프로필 양식 구성 요소에 대한 유효성 검사 규칙을 테스트하려고 합니다.
Livewire 파사드를 사용하는 대신 Pest Livewire 플러그인의
livewire()
기능을 사용할 수 있습니다. 테스트하려는 Livewire 구성 요소 클래스를 전달한 다음 평소처럼 set, call, assertSet 등과 같은 다른 메서드를 연결할 수 있습니다.<?php
// use ...
it('tests the ProfileForm validation rules', function () {
livewire(ProfileForm::class)
->call('save')
->assertHasErrors();
})
데이터 공급자를 사용하는 대신 Pest에는 테스트를 위해 데이터 세트를 연결하는 방법
with()
이 있습니다. 이것을 inline dataset이라고 합니다.dataset('my-dataset', [])
를 사용하여 재사용 가능한 shared datasets을 만든 다음 with('my-dataset')
다음에 it()
에서 호출할 수도 있습니다.데이터 세트는 배열이지만 PHP Unit 데이터 공급자에 따라 각 데이터 세트 항목에 대한 설명을 설정하여 어떤 데이터 세트가 통과하고 어떤 데이터 세트가 실패할 수 있는지 쉽게 이해할 수 있도록 하는 것이 좋습니다.
이제 우리는 그것을 모두 모아 완성된 테스트를 만들 수 있습니다.
<?php
use App\Http\Livewire\ProfileForm;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use function Pest\Livewire\livewire;
uses(RefreshDatabase::class);
it('tests the ProfileForm validation rules', function (string $field, mixed $value, string $rule) {
$user = User::factory()->create();
$anotherUser = User::factory()->create(['email' => '[email protected]']);
$this->actingAs($user);
livewire(ProfileForm::class, ['user' => $user])
->set($field, $value)
->call('save')
->assertHasErrors([$field => $rule]);
})->with([
'name is null' => ['user.name', null, 'required'],
'name is too long' => ['user.name', str_repeat('*', 201), 'max'],
'email is null' => ['user.email', null, 'required'],
'email is invalid' => ['user.email', 'this is not an email', 'email'],
'email is not unique' => ['user.email', '[email protected]', 'unique'],
'bio is null' => ['user.bio', null, 'required'],
'bio is too short' => ['user.bio', str_repeat('*', 8), 'min'],
'bio is too long' => ['user.bio', str_repeat('*', 1001), 'max'],
]);
기타 해충 기능
사용 가능한 모든 기능을 보려면 Pest 문서를 읽어보십시오. 아직 직접 사용을 시작하는 중이지만 제가 찾은 정말 멋진 기능 중 하나는 실행
beforeEach()
기능으로 한 가지 방법으로 설정을 수행할 수 있으며 다음에서 실행before each 테스트됩니다. 파일.이에 대한 예는 관리 사용자가 필요한 모든 테스트에 대해 관리 사용자를 생성하는 것입니다. 파일의 각 테스트는
$this->adminUser
에 액세스할 수 있습니다.<?php
use App\Models\User;
use function Pest\Laravel\get;
beforeEach(function () {
$this->adminUser = User::factory()
->create(['is_admin' => true]);
});
it('allows an admin to view manage users page', function () {
actingAs($this->adminUser)
->get('/manage-users')
->assertOk();
});
Reference
이 문제에 관하여(Pest를 사용하여 Laravel Livewire 유효성 검사 규칙 테스트), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/chrisrhymes/using-pest-to-test-laravel-livewire-validation-rules-56i8텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)