PHPUnit을 사용하여 Laravel에서 DOM 테스트

王林
풀어 주다: 2024-07-22 09:06:42
원래의
402명이 탐색했습니다.

Test Your DOM in Laravel with PHPUnit

PHPUnit comes out of the box with features like AssertSee and AssertSeeText in both cases we can assert against a specific text, to assert HTML tags we are going to rely on these features with some custom work to polish these a little bit more.

Case of use

I need to test that some forms generate a CSRF token.

Basic Solution

Laravel CSRF token directive generates an input like this:


로그인 후 복사

As the generated token changes between requests we are not going to test the generated token value, instead we are going to assert that the input exists with some of the attributes required, PHPUnit assertSee has second param to escape a value so we can do something like this:

$this
    ->get("contact-us")
    ->assertSee([
        '
로그인 후 복사

Improving iteration

It would solve our solution, but probably there is a better way to use this for more cases, so writing using a "wishful thinking" approach my desired code would be something like this:

$this->get("contact-us")
    ->assertHtml('input', [
        "type" => "hidden",
        "name" => "_token",
])
로그인 후 복사

This would be useful as it adds an assertion that would work in multiple cases by only passing the tag name and an array of attributes

We can add something like this in Laravel by adding a custom macro to the TestResponse class in the AppServiceProvider or any other custom Provider:

TestResponse::macro('assertHtml', function ($tag, $attributes) {
    $attributes = collect($attributes)
        ->map(function ($attributeValue, $attributeKey) {
            return "$attributeKey=\"$attributeValue\" ";
        })
        ->values()
        ->implode("", "");

        $htmlElement = "<$tag $attributes";
        $this->assertSee([$htmlElement], false);
});
로그인 후 복사

Now we can test our DOM by testing the presence of a tag and an attribute.

Aiming Laravelish Way

We can go a little bit forward in this case, I would need to assert that a form as CSRF tokens in multiple forms in the app, so we can rely on our macro to create more assertions, in this case as the expected HTML tag and attributes would not change I can add something like this:

TestResponse::macro('assertCSRFTokenExists', function () {
    $this->assertHtml('input', [
        "type" => "hidden",
        "name" => "_token",
    ]);
});
로그인 후 복사

This assertion is short, reusable, easy to read and use:

$this->get("contact-us")->assertCSRFTokenExists();
로그인 후 복사

For more powerful assertions you should consider an excellent package like:

sinnbeck/laravel-dom-assertions

Hopefully, this helps to add basic DOM assertions in your tests

위 내용은 PHPUnit을 사용하여 Laravel에서 DOM 테스트의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!