Cypress xpath plugin does not work with cy.type()

345 Views Asked by At

I am unable to figure out why the cypress xpath is not working with the type(). I have two command functions: one that looks for the element using cy.get() and one that uses cy.xpath(). Unfortunately, this is a dynamic field so I have to use xpath.

(https://i.stack.imgur.com/wXl9q.png)

This is how I am using the above command.

(https://i.stack.imgur.com/snVn7.png)

Error:

(https://i.stack.imgur.com/08G32.png)

I tried to reading the cypress docs and searching on the internet, however the examples for solutions did not work. I am on on Electron version: 21.0.0, Bundled Node version: 16.16.0

2

There are 2 best solutions below

1
On

The answer is in your error message - you're trying to use cy.type() but the previous command (cy.xpath()) is yielding more than one element. I would focus on figuring out what differentiates the field you want to type in from the others found by cy.xpath(). If there is nothing different between them, then you can simply select the correct element by the 0-index of the element.

cy.xpath(element).eq(0).type(value); // assumes the first element yielded by cy.xpath
1
On

I think you are mistaken about the results of your xpath expression.

You have used //div[5]/div[1]/input which can return multiple elements.

The // predicate will "select all" if they are present.

Only / predicate is guaranteed to return a single element.

Since Cypress is telling you it found multiple elements, it is more likely that your selector is wrong than the Cypress library.

You will have to change the xpath selector.