Skip to content

Asserting text in nested elements #19

@jakobbuis

Description

@jakobbuis

I have a use case for asserting a node contains a string, including any node's children. I'm currently using a custom trait using querypath.

trait HTMLAssertions
{
    /**
     * Assert that a given element, or any of its children contains the given text
     * @param  string $text     the text to check for
     * @param  string $element  HTML5 blob
     * @param  string $selector selector to scope the search to
     * @param  string $message  optional message when the assertion fails
     * @return void
     */
    public function assertElementContains(string $text, string $element, string $selector, ?string $message = ''): void
    {
        $this->assertStringContainsString($text, $this->parseToSelector($element, $selector), $message);
    }

    /**
     * Assert that a given element, or any of its children not contains the given text
     * @param  string $text     the text to check for
     * @param  string $element  HTML5 blob
     * @param  string $selector selector to scope the search to
     * @param  string $message  optional message when the assertion fails
     * @return void
     */
    public function assertElementNotContains(string $text, string $element, string $selector, ?string $message = ''): void
    {
        $this->assertStringNotContainsString($text, $this->parseToSelector($element, $selector), $message);
    }

    private function parseToSelector(string $element, string $selector): string
    {
        return html5qp($element, $selector)->text();
    }
}

A simple approach: parse the HTML-string, find the selector, get node text contents, use string matching.

I'm considering making it a dedicated package, but it could be a fit for including it here? Let me know if this is of interest, before I rewrite it to a pull request. :)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions