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?
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With