1

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.

1 Answer 1

3

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 
Sign up to request clarification or add additional context in comments.

4 Comments

I've seen this example but they are implementing as() in before(). If I try to set alias inside of it() then this.myAlias throws Trying to get myAlias of undefined. But cy.get("@myAlias") seems working.
You should generally use cy.get("@thing") rather than the this syntax anyways. this can create confusion and errors with many elements (arrow functions, callbacks, events, etc.)
Very well explained. One more thing... As long as get() returns Promise. Can I be absolutely sure that cy.get(element).as("myAlias") is being fetched before cy.get("@myAlias") or there is chance that cy.get("@myAlias") is going to be undefined?
If you run two cy.get one after the other, the second one will start only once the first one is done. So if the first one defines the alias, either: it gets the alias and then moves on, or the tests fails because the first get failed. So normally you won't have any issue

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.