No votes yet.
Please wait...

To start using XPath selectors, you should install a special plugin.

We mean a licensed plugin from Cypress.

It is installed in a typical way — the command npm install D cypress-xpath is executed to install the required package.

Next, you need to add the cypress-xpath function to the cypress/support/index.js file.

If it’s not done, the plugin won’t be registered and a user will see a message saying that cy.xpath is not a function.

If users use TypeScript, they need to add cypress-xpath to tsconfig.jsonfile files.

This action will help add the xpath () command that works together with the .get command.

It helps return the HTML element that you may use in your further work.

Further, we’ll analyze some examples of XPath and try to analyze how they are used on the basis of Cypress commands (e.g. while offering security testing services).

An example of Cypress/XPath

Selecting the entire document:

cy.xpath(‘/html’)

cy.root()

Selecting an object by certain text:

cy.xpath(‘//*[text()[contains(.,”My Lists”)]]’)

cy.contains(‘My Lists’)

cy.xpath(‘//*[@data-cy=”create-board”]’)

cy.get(‘[data-cy=”create-board”]’)

Selecting an element that contains the required class:

cy.xpath(‘//*[contains(@class, “font-semibold”]’)

cy.get(‘.font-semibold’)

Note! This XPath selector completely corresponds to random settings inside the class attribute.

Therefore, if the X element contains the button_front-semibold class name, this XPath selector will also find it.

Selecting an element with a certain class by text:

cy.xpath(‘//*[contains(@class, “font-semibold”)][text()[contains(.,”My Lists”)]]’)

cy.contains(‘.font-semibold’, ‘My Lists’)

Filtering an object by index:

cy.xpath(‘(//div[contains(@class, “list”)])[1]’)

cy.get(‘.list’).eq(0)

Keep in mind that the XPath selector doesn’t start with 0 as in other languages but from 1.

Searching for a child element:

cy.xpath(‘//div[contains(@class, “list”)]//child::div[contains(@class, “card”)]’)

cy.get(‘.list’).find(‘.card’)

And finally, we’ll analyze a process of selecting an element that contains a certain set of child elements:

cy.xpath(‘//div[contains(@class, “list”)][.//div[contains(@class, “card”)]]’)

cy.get(‘.card’).parents(‘.list’)

Leave A Comment