Skip to main content

Cypress XPath Plugin

In this article, we will witness how we can use XPath in Cypress. Cypress does not have default support for XPath, It can be done with the help of a plugin. Follow below steps to install and use Cypress XPath plugin:

Step 1: Install Cypress XPath Plugin

Using NPM

$ npm install cypress-xpath

Using Yarn

$ yarn add cypress-xpath --dev

 We can see here in the package.json that the XPath package has been installed successfully.

Step 2: Add plugin to support / index.js

Now go to the support folder and index.js and do the following and save.

require('cypress-xpath')

Step 3: XPath Usage

Now that is done, let us see how we can use this in real-time action. For this, we will do a simple login functionality on our traditional https://www.programsbuzz.com/user/login  site.

  1. We are going to visit the site.
  2. Use within context and enter inside the form area of the username and password field.
  3. Type in the fields.

That's it.

describe('Xpath Trial',()=>{
    before(() => {
        cy.visit('https://www.programsbuzz.com/user/login')
        
        })
        it('Type Username And Password',()=>{
            cy.get('form').within(()=>{
                cy.xpath("//input[@id='edit-name']").type('Naruto')
                cy.xpath("//input[@id='edit-pass']").type('Boruto')
            })
        })
})

To use XPath, simply do cy. And then XPath to invoke the XPath package and use the selector.

how to use xpath in cypress

We can see that the test passed with the XPath selector and successfully sent keys into the fields.

Conclusion:

However, we would advise choosing the native selector over XPath as the XPath selector is relatively slower than the native selector.

Cypress Xpath IntelliSense support

Add the following line in your spec file for intelliSense support

/// <reference types="cypress-xpath" />

Cypress XPath TypeScript

For typescript add below json to tsconfig.json

{
  "compilerOptions": {
    "types": ["cypress", "cypress-xpath"]
  }
}

Video: How to Use XPath in Cypress

Tags
Submitted by arilio666 on March 2, 2022

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.