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 ??
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)
})
@MikhailBolotov is correct, synchronous code like Cypress.$ in the same block as commands runs first.
Try out out this simple visit and heading check.
it('asynchronous commands', () => {
cy.visit('http://example.com')
.then(() => console.log('After visit'))
var elmText = Cypress.$('h1').text()
cy.log(elmText)
console.log('At end of test')
})
The order of console.logs is
As well as @MikhailBolotov'a suggestion, you can use hooks like beforeEach to break up the block and achieve what you want.
beforeEach(() => {
cy.visit('http://example.com')
.then(() => console.log('After visit'))
})
it('asynchronous commands', () => {
var elmText = Cypress.$('h1').text()
cy.log(elmText)
console.log('At end of test')
})
The order of console.logs is now correct