Search code examples
behatmink

How to select the element in HTML tags based on its text in Behat?


I'm running the following Behat scenario:

Then I should see "Testing body" in the "strong" element

for the following HTML snippet:

<strong>Testing body</strong>

However I am getting an error:

The text "Testing body" was not found in the text of the element matching css "strong"

What is the best way to check if element contains below tags?

<em>Testing body</em>
<ol><li>Testing body</li>
</ol>
<ul><li>Testing body​​​​​​​</li>
</ul>

I am trying to use wysiwyg.feature with syntax:

Then I should see "Testing body" in the "<Element>" element with the "<Property>" CSS property set to "<Value>" in the "Pearson Content" region

Solution

  • Make sure the selector used is unique.

    Depending on the method used you might need id|name|label|value or css selector.

    I your case the selector used is too general, you need to narrow the section by adding an extra element in front of this to tell him to search in a smaller section.

    For example: #myid strong -> will search strong in the element that has the id myid

    Same thing for the other elements, you could have ol>li or ul>li, but if more elements are found you will need to add an extra selector in front to narrow the section.

    Always check the CSS manually in the browser and make sure is unique or the element that you need is found first.

    If you want to check for an element that contains some text, you could use XPath like this:

    //strong[contains(text(), 'Testing body')]
    

    You can also use a css if you can identify this section as I said above, but I need more from the html, a large section in order to get a better selector.