XPath Error in Mink: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type

StackOverflow https://stackoverflow.com/questions/21945754

  •  14-10-2022
  •  | 
  •  

Question

I'm using Mink and the Selenium2 Driver with Behat to run some acceptance tests and for the most part, everything is going well.

However, I'm trying to target an element based on a data-* attribute with XPath, and the test chokes on it.

I've used XPathHelper and FirePath and my XPath checks out in both of those extensions:

//html//@data-search-id='images'

That appears to target the correct element.

However, when I add the following to FeatureContext.php

$el = $this->getSession()->getPage()->find('xpath', $this->getSession()->getSelectorsHandler()->selectorToXpath('xpath', "//@data-search-id='images'"));
$el->click();

I get the following error from Behat:

invalid selector: Unable to locate an element with the xpath expression
//html//@data-search-id='images' because of the following error:

TypeError: Failed to execute 'evaluate' on 'Document':
The result is not a node set, and therefore cannot be converted
to the desired type.
Was it helpful?

Solution

Your XPath expression is a totally valid expression – it will find all @data-search-id attributes and return true if one of them is 'images', otherwise false.

But you want to click an item, and obviously clicking a boolean value is rather difficult. Query for the item fulfilling the condition instead (thus, move the comparison into a predicate):

//html//*[@data-search-id='images']

Additionally, I'd remove the //html. The HTML node must be the root node anyway, so /html would have been fine (no reason for searching it in all subtree). As you're searching for an arbitrary descendent of it, and this will not be the root node (as <html/> is), omitting it completely does not change the meaning of the XPath expression.

//*[@data-search-id='images']

OTHER TIPS

I think the XPath you're looking for is:

//html//*[@data-search-id='images']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top