Skip to content

Instantly share code, notes, and snippets.

@tanakahisateru
Last active June 13, 2022 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanakahisateru/7f9a8b7580adb74862ffb1232d73bef5 to your computer and use it in GitHub Desktop.
Save tanakahisateru/7f9a8b7580adb74862ffb1232d73bef5 to your computer and use it in GitHub Desktop.
assertHtmlStringEqualsHtmlString
<?php
/**
* @method assertEquals(mixed $expected, mixed $actual, string $message)
*/
trait AssetHtmlTrait
{
public function assertHtmlStringEqualsHtmlString(string $expectedHtml, string $actualHtml, string $message = ''): void
{
$expected = (new \PHPUnit\Util\Xml\Loader)->load(
$this->cleanHtml($expectedHtml),
true
);
$actual = (new \PHPUnit\Util\Xml\Loader)->load(
$this->cleanHtml($actualHtml),
true
);
$this->assertEquals($expected, $actual, $message);
}
protected function cleanHtml(string $html): string
{
$html = preg_replace(['/>\s+/', '/\s+</'], ['>', '<'], $html);
return preg_replace('/\s+/', ' ', $html);
}
}
<?php
class ExampleTest
{
use AssetHtmlTrait;
public function testSomeOperation()
{
$actual = sprintf(<<<HTML
<div><a href="%s" title="%s">link</a></div>
HTML, "https://example.com", "example.com");
// You can check HTML equivalence:
$this->assertHtmlStringEqualsHtmlString(<<<HTML
<div>
<a
title="example.com"
href="https://example.com"
>link</a>
</div>
HTML), $actual);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment