How to use xpath in cypress in simple step

In this article, we will cover how to use xpath in cypress.

Cypress being a tool to the automated testing tool world, and most of us come from the selenium world, We are habitant to use xpath to identify the elements in an application. Cypress backed by javascript offers only CSS capability to capture elements, which is difficult for some of us.

To overcome this hassle, we can incorporate a plugin that allows using xpath in our cypress framework.

Let’s see in action, how we can implement xpath locator in cypress.

Firstly we need to install xpath plugin with npm command

npm install -D cypress-xpath
xpath  in cypress

After successful installation, as shown above, we need to incorporate in support file with npm command.

Add the below lines in cypress/support/index.js


Now, we are done with the setup.

Let’s take a look at the test case

Before Xpath implementation

xpath  in cypress

After implementation of xpath,

describe('example to-do app', () => {
  beforeEach(() => {
  it('displays first', () => {

    cy.xpath('/html/body/section/div/section/ul/li').should('have.length', 1)


  it('displays second', () => {

    cy.xpath('/html/body/section/div/section/ul/li').should('have.length', 2)



Testcase created with xpath provides the way result as that of CSS element.

xpath  in cypress

We successfully implemented a way to identify elements with xpath for your first testcase. We hope it is useful. Happy Automating.

Leave a Reply