Configure XPath plugin in Cypress

Tutorial 20​​ ​​ Configure XPath plugin in Cypress ​​​​ 

In this tutorial we will see, how to use xpath in cypress. We know that, by default, cypress uses css selector. However, if you have expertise in creating Xpaths instead of css selectors,​​ it is possible in cypress as well. We have to simply install xpath plugin in cypress.

Just search for ‘install xpath plugin in cypress’. You will get a GitHub link, see below

Click the GitHub link, it will take you to
https://github.com/cypress-io/cypress-xpath​​ ​​ 

Scroll down the page a liitle bit, you would see an npm command to install​​ xpath

Now, go to the cypress working directory location

Type cmd​​ 

Hit Enter

The Microsoft windows command line opens

Next copy the npm command

Paste it in command prompt

Hit Enter

As seen above, the xpath plugin gets installed.

Next, we will add the​​ cypress-xpath in index.js file. This index.js file is present inside cypress/support directory,​​ see below

Open the visual code editor, you would see the ‘support’ folder as seen below

Expand the ‘support’ folder. You would see index.js file

Next, copy the line

Paste it in index.js, see line 21 below​​ 

Save the index.js file.

Now we will create a simple test case​​ in cypress​​ using xpath.​​ We will be launching​​ https://www.google.com/​​ and we will click ‘Images’ link.​​ 

Let us inspect the ‘Images’ link, it is represented by ‘a’ tag and has the text ‘Images’

So the custom xpath would be​​ //a[text()='Images']

However, let us first use an incorrect xpath​​ (line 6 below)​​ so that the Test fails​​ and we get the xpath error.​​ We have to use cy.xpath​​ method if we want to use xpath with cypress, see below​​ 

Open the Test runner

Click xpath.spec.js

Notice that the Test fails​​ as expected (sice our xpath was incorrect)

Let us now use the correct xpath

Save the file.

The Test gets re-executed.​​ This time the ‘Images’ link gets clicked & the Test gets passed. This means that xpath plugin is working fine.

So now you are all set to start using xpaths in cypress scripts!

Thank you​​ for reading!

Share On

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on tumblr
Share on email

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Lifetime Membership Club

LIFETIME MEMBERSHIP BIG SALE - ALL LIVE COURES JUST - 7000 RS/ 99 USD
Attend All Live courses in just 7000 rs / $99 - offer ends 1st Nov 2024