Reputation: 8531
I'm trying to store Cypress element in variable and re-use it instead of calling get()
again.
My first unsuccessful attempt:
// works
const wrap = cy.get(`wrapSelector`)
wrap.should('be.visible')
// works
const input = wrap.find(`input`)
input.should('be.focused');
input.type(string);
// wrap is now `input` (line 6) instead of `wrapSelector` (line 2)
const button = wrap.find('button').click();
// @error: button not found in `input`
So I've read Cypress closures and I've tried using then()
. But it returns jQuery object.
cy.get(`someSelector`).then($wrap=>{
// now I would like to test $wrap
// but $wrap is now jQuery object so I can't do this:
$wrap.should('be.visible')
// ... some code
})
It could be working if I would use whole selector with children but I am not sure if it's best practice
cy.get(`wrapSelector`).should('be.visible')
cy.get(`wrapSelector input`).should('be.focused')
cy.get(`wrapSelector input`).type(string);
cy.get(`wrapSelector button`).click()
// works
I know that I can test jQuery object too (for example with expect()
) but I would like to keep using should()
. What is the best practice when I would like to re-use some already fetched elements? Ideal solution on this example would be the best.
Upvotes: 1
Views: 10148
Reputation: 1594
You should be using aliases as mentioned by Cypress here: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Sharing-Context
because of the use of promises, Cypress methods do not return values directly. Aliasing allows you to:
cy.get(element).as("myAlias")
this.myAlias // works
cy.get("@myAlias") // works
Upvotes: 3