Home > Back-end >  assertSee failed due to whitespaces in html code
assertSee failed due to whitespaces in html code

Time:10-01

In my blade, I have a button:

<a
     href="/customer/member/delete/{{ $member->id }}"
     
>
          Delete
</a>

And I want to test it:

$this->view->assertSee('<a href="/customer/member/delete/1" >Delete</a>');

How can I ignore whitespaces in the test? A tried: trim and string_replace, but they have not solved the problem.

CodePudding user response:

You can split to strings and use false like second arguments to NOT escape:

It works from Laravel 7

$strings=[
    '<a',
    'href="/customer/member/delete/1"',
    '',
    '>',  // not strictly necessary, can be removed
    'Delete',
    '</a>'
];

$this->view->assertSeeInOrder($strings, false);

CodePudding user response:

Try this:

use Illuminate\Testing\Assert as PHPUnit;

    /**
     * Assert that the given string is contained within the rendered component without whitespaces.
     *
     * @param  \Illuminate\Testing\TestComponent  $haystack
     * @param  string  $needle
     * @param  bool  $escape
     * @return $this
     */
    public function assertSeeWithoutWhitespaces($haystack, $needle, $escape = true)
    {
        $value = $escape ? e($needle) : $needle;

        $value = preg_replace('/\s /', ' ', $value);
        $value = preg_replace('/\> /', '>', $value);
        $value = preg_replace('/ </', '<', $value);

        $withoutWhitespaces = preg_replace('/\s /', ' ', $haystack->render());
        $withoutWhitespaces = preg_replace('/\> /', '>', $withoutWhitespaces);
        $withoutWhitespaces = preg_replace('/ </', '<', $withoutWhitespaces);

        PHPUnit::assertStringContainsString((string) $value, $withoutWhitespaces);

        return $this;
    }

And you can use like this:

$this->assertSeeWithoutWhitespaces(
    $view,
    '<a href="/customer/member/delete/1" >Delete</a>',
    false
);

Now you can use whitespaces in your blade file and in your test string too.

You can extend preg_replace rules as you wish.

  • Related