Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit, asserting html content

Which is the best way to assert with phpunit certain content in html strings?

In Zend applications there are a buch of assertions assertQuery* available. But if you are not in a Zend application? assertXml* doesn't look to be appropiate.

For instance, how would you assert that the tag <div ... id="myId" ...>...</div> exists in $htmlString taking into account that changing the position of the id attribute wouldn't fail the test?

like image 433
Al_ Avatar asked Sep 05 '13 18:09

Al_


1 Answers

I suggest that you parse the HTML string using some library, and then use the library API for writing assertions.

There are lots of good HTML/XML parsers, for example:

http://symfony.com/doc/current/components/dom_crawler.html

Using this you can access any desired node by using CSS selectors, xpath, etc, and you can check if an attribute exists independently of it's position.

$crawler = new Crawler($html);
$this->assertEquals(1, $crawler->filter('div#elementId')->count());

You could also write a custom assertion that automates this process so that the assertion would be:

$this->assertHtmlContainsSelector($html, 'div#elementId');
like image 75
gontrollez Avatar answered Nov 06 '22 03:11

gontrollez