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?

1 Answer 1

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.

1
  • 1
    See also this solution, which uses PHPUnit's assertXML family of functions.
    – bishop
    Jan 7, 2015 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.