简体   繁体   中英

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?

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');

I had exactly the same problem and could not find a modern solution, so I came up with https://packagist.org/packages/phpfui/html-unit-tester

You basically want to run as much generated html and css through a validator as possible.

It is best not to validate against a template (unless you want to make sure nothing changes, but that is a different condition / test that you may want).

What you really care about is that your HTML (and CSS) is correctly formatted. This accommodates future functionality and data related changes. Your code must produce valid HTML and CSS.

https://packagist.org/packages/phpfui/html-unit-tester validates against w3.org standards, so will always be up to date with the latest HTML spec.

Really helpful unit testing to make sure you aren't doing something wacky that only works on the browser you wrote it against.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM