Home > Back-end >  Cypress.$('abc').text() returns undefined
Cypress.$('abc').text() returns undefined

Time:03-07

I am trying to find a text of element using Cypress.$ All is working well with cy object but the Cypress.$ yields undefined

//This works

cy.get('abc').eq(0).find('xyz').then(($elm)=>{
                cy.log("$elm=" $elm.text())
            })

//This yields "undefined"

var elmText = Cypress.$('abc').eq(0).find('xyz').text()
cy.log(elmText)

Can some one help why Cypress.$ does not works here ??

CodePudding user response:

I can only guess that you have some cypress commands that must be completed before querying the selector. As cypress commands are asynchronous, your UI state is not ready when jquery is executed. Thus, you can make it executed synchronously with cypress commands as follows:

cy.then(() => {
   var elmText = Cypress.$('abc').eq(0).find('xyz').text()
   cy.log(elmText)
})

CodePudding user response:

Cypress automatically includes jQuery and exposes it as Cypress.$. In your case Cypress.$('abc') will create a promise that has to be resolved, hence we have to use cy.wrap(). You can read more about this from cypress docs. You can do something like this:

const $ele = Cypress.$('abc')
cy.wrap($ele).eq(0).find('xyz').text()

You can also use aliases and then later acces them with this.

cy.get('abc').eq(0).find('xyz').invoke('text').as('someText')
cy.log(this.someText) //prints the saved text`
  • Related