0

I want to make common function in cypress automation for that, I want to use the locators and xpath to find the element but I am facing issue using indexes in xpath cypress.

In selenium automation, it is easy to create parameterized xpath but in cypress facing issues?

2 Answers2

0

Cypress does not support xpath directly. You have to use the xpath plugin. See here for more details on how to add this plugin to your project.

After that, you will be able to call the xpath command. For using indexes, you can write something like the following:

      for (const i of [1,2,3]) {
        cy.xpath(`(//button[contains(text(), 'Done')])[${i}]`)
      }

If you need to parameterize your expression, you can define a function:

      function containsAtIndex(i) {
        return cy.xpath(`(//button[contains(text(), 'Done')])[${i}]`)
      }

Or define a custom cypress command. With the Cypress Support Pro plugin, it's easy and can be done in a couple of clicks: enter image description here

Mikhail Bolotov
  • 976
  • 1
  • 6
  • 13
  • Yes, I know about the xpath plugin. Thank you for the solution. – Aayush Khandelwal May 09 '22 at 20:47
  • There is one more question, if we define our XPath at the top of the file with this "[${i}]" then how we will pass the value from the method to get the exact button. Please let know, if any solution because I am following the POM design pattern for that I want to pass the index value from the method itself. – Aayush Khandelwal May 10 '22 at 22:26
  • You can use either a function or a custom command. I updated the answer with – Mikhail Bolotov May 11 '22 at 12:32
0

You can use eq to specify the index.

In your example it will look like this: cy.contains('button', 'Done').eq(2)