#development #laravel #php #testing

Today, I was adding tests for some Blade templates in Laravel.

One of the things I wanted to assert is that the output contained a specific piece of HTML.

I first tried:

 1use Tests\TestCase;
 2
 3class ExternalFlowControllerTest extends TestCase
 4{
 5  /** @test */
 6  public function it_contains_a_specific_html_snippet(): void
 7  {
 8      $this->get('/my/endpoint')
 9          ->assertSee("<input type=\"hidden\" name=\"id\" value=\"expected\">");
10  }
11}

That however didn't work as expected, returning the following error instead:

Expected: <!DOCTYPE html>\n
  <html lang="en">\n
  <head>\n
  ... (62 more lines)

  To contain: &lt;input type=&quot;hidden&quot; name=&quot;id&quot; value=&quot;expected&quot;&gt;

The fix is really easy, there is a second parameter you can add to the assertSee function to indicate that the output should not be escaped. It defaults to true, so you need to set it to false to avoid the escaping.

Assert that the given string is contained within the response. This assertion will automatically escape the given string unless you pass a second argument of false.

 1use Tests\TestCase;
 2
 3class ExternalFlowControllerTest extends TestCase
 4{
 5  /** @test */
 6  public function it_contains_a_specific_html_snippet(): void
 7  {
 8      $this->get('/my/endpoint')
 9          ->assertSee("<input type=\"hidden\" name=\"id\" value=\"expected\">", escape: false);
10  }
11}

If you simply want to test for the presence of text, ignoring the HTML, you can use the assertSeeText function instead.

Assert that the given string is contained within the response text. This assertion will automatically escape the given string unless you pass a second argument of false. The response content will be passed to the strip_tags PHP function before the assertion is made.