Home > Software design >  How to store the number(length) of similar xpath in a variable in Cypress
How to store the number(length) of similar xpath in a variable in Cypress

Time:10-19

I am trying to get the number(length) of similar xpath and store it in a variable

    cy.xpath('//tbody[@]/tr/td/div[@]/div[text()="28"]')
                .its('length').as("CountSimilar")
        cy.log( this.CountSimilar)
        var Nxpath = this.CountSimilar; 

Any idea how to store the length in a variable

CodePudding user response:

Cypress commands are asynchronous, so you have to use a then callback in order to give Cypress time to evaluate the variable. So you can write your code as follows:

cy.xpath('//tbody[@]/tr/td/div[@]/div[text()="28"]')
            .its('length').as("CountSimilar")
cy.get("@CountSimilar").then(CountSimilar => {
    cy.log(CountSimilar)
})

CodePudding user response:

Make sure you wrap your test in a function() to allow use of the alias variable this.CountSimilar.

it('tests Nxpath', function() {

  cy.xpath('//tbody[@]/tr/td/div[@]/div[text()="28"]')
    .its('length')
    .as("CountSimilar")                // adds variable the "this"

  cy.log(this.CountSimilar);           // "this" is defined when using function()
  var Nxpath = this.CountSimilar; 
  ...
})
  • Related