1

I am unit testing an HTML builder. I want to assert that the generated content matches the expected content, but I want some flexibility with respect to white space.

Specifically, I don't care if the white space between tags is tab indented or space indented or if it's all on one line. I only care about the tags, their order, their attributes, and their content.

How can I assert that two HTML fragments are equal?

bishop
  • 37,830
  • 11
  • 104
  • 139

1 Answers1

0

Self answering, as I didn't find this on SO anywhere:

/**
 * Compare two HTML fragments.
 */
protected function assertEqualHtml($expected, $actual)
{
    $from = ['/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '/> </s'];
    $to   = ['>',            '<',            '\\1',      '><'];
    $this->assertEquals(
        preg_replace($from, $to, $expected),
        preg_replace($from, $to, $actual)
    );
}

Based on a PHP implementation of an HTML minifier.

Community
  • 1
  • 1
bishop
  • 37,830
  • 11
  • 104
  • 139
  • 1
    See also [this solution](http://stackoverflow.com/questions/7167788/phpunit-asserting-identical-html-structure-regardless-of-whitespace), which uses PHPUnit's `assertXML` family of functions. – bishop Jan 07 '15 at 20:55