skip to Main Content

In my blade, I have a button:

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

And I want to test it:

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

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

2

Answers


  1. 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"',
        'class="btn btn-secondary delete-button"',
        '>',  // not strictly necessary, can be removed
        'Delete',
        '</a>'
    ];
    
    $this->view->assertSeeInOrder($strings, false);
    
    Login or Signup to reply.
  2. Try this:

    use IlluminateTestingAssert as PHPUnit;
    
        /**
         * Assert that the given string is contained within the rendered component without whitespaces.
         *
         * @param  IlluminateTestingTestComponent  $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" class="btn btn-secondary delete-button">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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search