Search by

vinojcardoza / phpunit-html-assertions

vinojcardoza

PHPUnit assertions for testing HTML output: query rendered markup with CSS selectors and assert on elements, attributes and text.

Package info

github.com/vinojcardoza/phpunit-html-assertions

pkg:composer/vinojcardoza/phpunit-html-assertions

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-12-02 18:16 UTC

This package is auto-updated.

Last update: 2026-12-02 18:25:47 UTC


README

PHPUnit assertions for testing HTML output: query rendered markup with CSS selectors and assert on elements, attributes and text instead of brittle string matching.

Status: stable.

Requirements

  • PHP 8.4+
  • PHPUnit 12 or 13

Installation

Install it as a dev dependency, since it is only needed when running tests:

composer require --dev vinojcardoza/phpunit-html-assertions

Available assertions

  • assertElementExists($html, $selector): at least one element matches
  • assertElementNotExists($html, $selector): no element matches
  • assertElementCount($html, $selector, $expected): exactly $expected elements match
  • assertElementCountGreaterThan($html, $selector, $limit): more than $limit elements match
  • assertElementCountLessThan($html, $selector, $limit): fewer than $limit elements match
  • assertElementContains($html, $selector, $expected): at least one matching element contains the text
  • assertElementNotContains($html, $selector, $unexpected): elements match, and none contains the text
  • assertElementContentEquals($html, $selector, $expected): at least one matching element's whole text equals the text
  • assertElementContentNotEquals($html, $selector, $unexpected): elements match, and none has exactly the text
  • assertAttributeExists($html, $selector, $attribute): at least one matching element has the attribute
  • assertAttributeEquals($html, $selector, $attribute, $expected): at least one matching element has the attribute with exactly that value
  • assertValidHtml($html): the HTML isn't blank and the parser reports no errors

Every assertion also takes an optional custom failure message as its last argument.

Usage

Create an HtmlAssertions instance and call its assertions from a PHPUnit test:

use HtmlAssertions\HtmlAssertions;
use PHPUnit\Framework\TestCase;

final class GreetingTest extends TestCase
{
    public function testRendersMessage(): void
    {
        $html = '<html>
        <body>
            <p class="message">Hello World!</p>
            <p>Hello Crawler!</p>
        </body>
        </html>';

        $htmlAssertions = new HtmlAssertions();

        $htmlAssertions->assertElementExists($html, 'p.message'); // passes
        $htmlAssertions->assertElementExists($html, 'div');       // fails the test
    }
}

Elements that must not exist

assertElementNotExists() is the opposite: the selector must not match any element.

$htmlAssertions->assertElementNotExists($html, '.error');

Counting elements

assertElementCount() checks that a selector matches exactly the given number of elements. Zero is allowed; a negative count throws InvalidArgumentException.

$htmlAssertions->assertElementCount($html, 'p', 2);

assertElementCountGreaterThan() and assertElementCountLessThan() check that a selector matches more than, or fewer than, the given number of elements. The number itself doesn't pass. A limit that makes no sense throws InvalidArgumentException: a negative one for assertElementCountGreaterThan(), or one below 1 for assertElementCountLessThan().

$htmlAssertions->assertElementCountGreaterThan($html, 'p', 1); // 2 or more
$htmlAssertions->assertElementCountLessThan($html, 'p', 5);    // 4 or fewer

Text in elements

assertElementContains() checks that at least one element matching the selector contains the given text. The comparison is case-sensitive and includes text from descendants. Each run of whitespace in the element's text counts as a single space, so indentation in the markup doesn't matter. Empty expected text throws InvalidArgumentException.

$htmlAssertions->assertElementContains($html, 'p.message', 'Hello');

assertElementNotContains() checks that no element matching the selector contains the given text, compared the same way. At least one element must match: if none does, the assertion fails, so a mistyped selector doesn't pass unnoticed. Empty text throws InvalidArgumentException.

$htmlAssertions->assertElementNotContains($html, 'p', 'Goodbye');

assertElementContentEquals() is stricter than assertElementContains(): the whole text of at least one matching element must equal the given text. Text is read the same way, with surrounding whitespace removed. Empty expected text is allowed, and matches an element without text.

$htmlAssertions->assertElementContentEquals($html, 'p.message', 'Hello World!');

assertElementContentNotEquals() checks that no element matching the selector has exactly the given text, compared the same way. As with assertElementNotContains(), at least one element must match. Pass an empty string to check that no matching element is blank.

$htmlAssertions->assertElementContentNotEquals($html, 'p', 'Hello');
$htmlAssertions->assertElementContentNotEquals($html, 'p', '');

Attributes

assertAttributeExists() checks that at least one element matching the selector has the given attribute, whatever its value. Attributes without a value, such as disabled, count too. The name is case-insensitive, and an empty name throws InvalidArgumentException.

$htmlAssertions->assertAttributeExists($html, 'p', 'class');

assertAttributeEquals() also checks the value: at least one matching element must have the attribute with exactly the given value, including case and whitespace. Entities are decoded first, so &amp; in the markup is & in the expected value. An empty expected value matches alt="" and disabled, but not a missing attribute.

$htmlAssertions->assertAttributeEquals($html, 'p', 'class', 'message');

Valid HTML

assertValidHtml() checks that the HTML isn't blank and that PHP's HTML5 parser reports no errors in it, such as most stray end tags, misnested elements or unknown entities.

$htmlAssertions->assertValidHtml($html);

It accepts whole documents and snippets, so a missing doctype is not an error. A snippet can start with part of a table, such as <tr>, but a <tr> inside a <div> fails.

This is a syntax check, not a replacement for a full validator such as the W3C's. The parser doesn't report every mistake: an unclosed <div>, a stray end tag of a formatting element such as </em>, duplicate attributes, duplicate ids and unknown elements all pass.

Custom failure messages

Every assertion takes an optional last argument: a failure message that replaces the default one.

$htmlAssertions->assertElementExists($html, 'table', 'The page should have a table.');
$htmlAssertions->assertElementCount($html, 'li', 3, 'The menu should have three items.');

The assertion classes in HtmlAssertions\Assertions take the same message as their last constructor argument:

use HtmlAssertions\Assertions\AssertElementExists;

(new AssertElementExists($html, 'table', 'The page should have a table.'))->assert();

Without a custom message, the failures read:

Failed asserting that HTML contains an element matching "table".
Failed asserting that HTML does not contain an element matching ".error"; found 1.
Failed asserting that HTML contains 3 element(s) matching "li"; found 2.
Failed asserting that HTML contains more than 3 element(s) matching "li"; found 2.
Failed asserting that HTML contains fewer than 2 element(s) matching "li"; found 2.
Failed asserting that an element matching "p" contains "Goodbye"; found "Hello World!", "Hello Crawler!".
Failed asserting that an element matching "table" contains "Goodbye"; no element matched.
Failed asserting that no element matching "p" contains "World"; found "Hello World!".
Failed asserting that the content of an element matching "p.message" equals "Hello"; found "Hello World!".
Failed asserting that the content of no element matching "p" equals "Hello World!"; found 1.
Failed asserting that an element matching "p" has the attribute "id"; found 2 without it.
Failed asserting that an element matching "p" has the attribute "class" equal to "error"; found "message".
Failed asserting that HTML is valid; found 1 error(s):
- line 3, column 5: tree error unexpected-closed-token

PHPUnit adds its own comparison line after the message, such as Failed asserting that false is true. or Failed asserting that 2 is identical to 3.

Selectors

By default a selector is a CSS selector, such as h2, .card, #title, a[href="/more"] or .card a.button.

To use XPath, prefix the expression with xpath: (the prefix is case-insensitive):

$htmlAssertions->assertElementExists($html, 'xpath://a[@href="/more"]');

The selector must select elements. An XPath expression that returns attributes, text nodes or a scalar value, such as xpath://a/@href or xpath:count(//a), is rejected.

How HTML is parsed

Every assertion accepts a whole document or just a snippet, such as the output of one template or component:

$htmlAssertions->assertElementContains('<li class="active">Home</li>', 'li.active', 'Home');
$htmlAssertions->assertElementCount('<tr><td>One</td><td>Two</td></tr>', 'td', 2);

A browser drops table parts (<tr>, <td>, <tbody> and so on) that aren't inside a table. When a snippet starts with one, it is parsed inside a temporary table, which is then removed, so selectors match only your own elements. As in a browser, a snippet is still placed in an <html> document with a <head> and <body>, so those selectors always match.

The HTML is parsed with PHP 8.4's HTML5 parser (Dom\HTMLDocument), the same way a browser parses it, and read as UTF-8. Malformed markup is repaired rather than rejected, so <div><p>Hi</div> works. Use assertValidHtml() to check for malformed markup. Elements are kept out of the XHTML namespace, so plain XPath such as //p matches them.

Errors

A failed assertion fails the test through PHPUnit (AssertionFailedError).

Input that can't be used throws an exception, which PHPUnit reports as a test error rather than a failure:

  • HtmlAssertions\Exceptions\InvalidSelectorException when:
    • the CSS selector is invalid, for example div[
    • the XPath expression is empty or can't be evaluated
    • the selector matches something other than elements
  • HtmlAssertions\Exceptions\InvalidHtmlException when the HTML can't be loaded at all (rare, because malformed markup is repaired)
  • InvalidArgumentException when the expected count passed to assertElementCount() is negative, the limit passed to assertElementCountGreaterThan() is negative or to assertElementCountLessThan() is below 1, the text passed to assertElementContains() or assertElementNotContains() is empty, or the attribute name passed to assertAttributeExists() or assertAttributeEquals() is empty

Development

composer install
composer test        # run the PHPUnit tests
composer lint        # check coding standards (phpcs)
composer lint:fix    # fix coding standards (phpcbf)
composer analyse     # static analysis (PHPStan, level 8)
composer quality     # lint + analyse
npx gulp             # watch src/ and run phpcbf, phpcs and PHPStan on save

Contributing

Contributions are welcome. See CONTRIBUTING.md for how to report bugs, set up the project and open a pull request. This project follows the Contributor Covenant Code of Conduct.

To report a security problem, follow the security policy rather than opening a public issue.

License

Released under the MIT License.