This article is a part of series on Cypress basics. You can check out some other articles on my blog where I provide step by step explanations of some Cypress basics + some extra tips on how you can take things one step further. So far, I wrote about:
Let me start right of the bat stating that I’m not the biggest fan of xpath selectors. In my opinion, they are hard to read, and provide little benefits in comparison to CSS selectors or data-* attributes. With jQuery bundled into Cypress, you can select your elements in a much more readable way. However, they are widely used and a go-to choice for projects where you don’t have access to the source code. That’s why it’s useful to have knowledge on how to use them.
To use xpath selectors, you must first install a plugin. It is an official plugin maintained by Cypress. The installation is pretty standard. Just npm install -D cypress-xpath
to install the package.
You then have to add require('cypress-xpath')
to your cypress/support/index.js
file. Without this, your plugin is not registered and you will get cy.xpath is not a function
error.
If you are using TypeScript, don’t forget to add cypress-xpath
to your types in tsconfig.json
file.
This will add an .xpath()
command, which works similarly to .get()
command. It will return an HTML element which you can then interact with. Let’s look into a couple of xpath examples and compare them to selector usage with Cypress commands.
As is usuall with my blog, you can check out the working code in my repository branch.
Important side note here. This xpath will match any substring in the class attribute, that means that if we had an element with a class name button_font-semibold
it would also be matched by this xpath selector.
Notice that xpath does not use the numbering from 0, as is often used in other languages, but starts numbering from number 1.
In this example, we want to select only the list that contains some cards:
Hope this helps. Share this with your friends if you feel like someone can learn from this, I’d greatly appreciate this.
If you want to learn more about selecting elements, I recommend checking out my other articles on selecting elements, autocompleting selectors or a very powerful .contains() command. Additionally, if you work with xpath, I recommend checking out Sanjay Kumar’s SelectorsHub tool.
From time to time I send some useful tips to your inbox and let you know about upcoming events. Sign up if you want to stay in loop.