What is cypress-xpath?
The cypress-xpath package is an extension for Cypress that allows you to use XPath selectors in your Cypress tests. This can be particularly useful for selecting elements in complex DOM structures where CSS selectors might be cumbersome or insufficient.
What are cypress-xpath's main functionalities?
XPath Selector
This feature allows you to use XPath expressions to select elements in the DOM. In this example, the XPath expression selects a button element with the text 'Submit' and performs a click action on it.
cy.xpath('//button[text()="Submit"]').click();
Chaining with Cypress Commands
You can chain XPath selectors with other Cypress commands. In this example, the XPath expression selects a div element with the class 'container', and then the find method is used to locate a button within that container and click it.
cy.xpath('//div[@class="container"]').find('button').click();
XPath with Variables
You can use variables within your XPath expressions. This example demonstrates how to use a variable to dynamically select a button based on its text content.
const buttonText = 'Submit';
cy.xpath(`//button[text()="${buttonText}"]`).click();
Other packages similar to cypress-xpath
cypress-selectors
The cypress-selectors package provides a way to use custom selectors in Cypress tests, including XPath. It offers a more flexible approach to element selection compared to cypress-xpath, allowing for the use of both CSS and XPath selectors interchangeably.
cypress-testing-library
The cypress-testing-library package extends Cypress's capabilities by providing a set of utilities for querying the DOM in a way that resembles how users interact with it. While it does not support XPath, it offers a more user-centric approach to element selection, which can be more intuitive for certain types of tests.
cypress-xpath

Adds XPath command to Cypress.io test runner
Install
npm install -D cypress-xpath
Then include in your project's cypress/support/index.js
require('cypress-xpath')
Use
After installation your cy
object will have xpath
command.
it('finds list items', () => {
cy.xpath('//ul[@class="todo-list"]//li')
.should('have.length', 3)
})
note: you can test XPath expressions from DevTools console using $x(...)
function, for example $x('//div')
to find all divs.
See cypress/integration/spec.js
Roadmap
License
This project is licensed under the terms of the MIT license.