Categories
PHP

Behat and Mink: Finding and clicking with XPATH and jQuery like CSS Selector

While doing acceptance tests, we often run into scenarios where we need to click on elements which can’t be found or clicked on using simple expressions like – I follow “Login”. Let me give an example, on a page there is an anchor tag with specific id. The anchor tag has no text but an image inside it. In such cases, we are left no other choices than querying the dom. XPath could be a decent way to find the anchor tag here. Let’s assume that the anchor tag has the id – 14. So the xpath query should be – “//a[@id=’14’]”.

PS: We can use Firebug to test out XPath queries. There is a built in function – $x – on a firebug console, just pass xpath queries as string to this function and it will throw matching elements.

Here’s a step definition I wrote inside my FeaturedContext class. This method takes in a xpath query and clicks on the element:

And how do we use it inside a “feature” file?

UPDATE:

Using a jQuery like CSS Selector is pretty easy. Looks like Mink also allows CSS Selectors by default. Here’s the same method with CSS Selector:

And we use it in the feature file like:

The test should fail in case a matching element was not found. Let me know if you run into any issues or find even better or elegant ways to do this.

9 replies on “Behat and Mink: Finding and clicking with XPATH and jQuery like CSS Selector”

Just
find() has first argument by some reason:

$session->find('xpath', $xpathSelector);
$session->find('css', $cssSelector);

To get the title of your html page:

$title = $this->getSession()->getPage()->find('css', 'title')->getText();

FLIP101

It is actually getHtml() not getText(), I am getting empty string for getText() when trying to access the <title> tag in Mink

invalid selector: The result of the xpath expression “//html//meta[@name =”description”]/@content” is: [object Attr]. It should be an element.

Comments are closed.