seleniumselenium-webdriverautomationcypresscypress-component-test-runner

How to perform the indexing for xpath in cypress automation?


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?


Solution

  • 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