Search code examples
symfonydomphpunitdomcrawler

Checking for a table row using DomCrawler


I am writing a phpunit test... on my page I have several rows, one of them is like this:

<tr><td>MATCH<small><span class="glyphicon glyphicon-pushpin"></span></small></td></tr>

Some are like this:

<tr><td>NOT A MATCH 1</td></tr>
<tr><td>NOT A MATCH 2</td></tr>
<tr><td>NOT A MATCH 3</td></tr>

how can I run a test to check that the row with the pushpin glyphicon is the one with "MATCH"?

Basically I want the test to confirm that the glyphicon is appearing on the correct row, and just having something like $crawler->filter('small:contains("' . $glyphCode . '")')->count() only confirms that the glyph exists - not that it's in the right place.

Any help appreciated, thank you.


Solution

  • You can use XPath Selectors with Symfony's DomCrawler.

    To select your desired element use this XPath expression:

    //td//small/span[@class="glyphicon glyphicon-pushpin"]
    

    Then place it inside a PHPUnit assertion.

    $this->assertEquals(1, 
       $crawler->filterXPath('//td//small/span[@class="glyphicon glyphicon-pushpin"]')->count()
    );
    

    I've used assertEquals 1 as expected value, to ensure that one element is found on the page.