The cypress docs(https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Elements) are pretty unclear on how alias and variables can be used to store information during a test.
I'm trying to store the text of a div on one page to use later, for example:
// let vpcName;
it('Store current name to use later', () => {
// save name for later use - doesn't work
// cy.get('#value').then(elem => {
// vpcName = Cypress.$(elem).text;
// });
// using alias - also doesn't work
cy.get('#value')
.invoke('text')
.as('vpcName');
});
it('Use previous value to return to correct page', () => {
cy.contains(this.vpcName).click();
});
I just came across this article that explains how and why you store a variable and then use it later in the "Cypress way":
https://www.stevenhicks.me/blog/2020/02/working-with-variables-in-cypress-tests/
In respect to how it should work, here is my example which first, collects the message (the message is shown for only 3 secs then disappears). Secondly, it gets the value using the @
sign. Lastly my code passes the stored message through to an empty function constructed to assert that the value Portsmouth
is contained within the message.
it('Current Port change', () => {
cy.get('#viewport').find('div[id=message]').then(message => {
let wags = message;
cy.wrap(wags).as('wags')
});
cy.get('@wags').then(wags => {
expect(wags).to.contain("Portsmouth")
});
});
let me know if you need further clarification
Try this:
cy.get('button').then(($btn) => {
const txt = $btn.text()
// $btn is the object that the previous command yielded
})
Source: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Return-Values
I had to resort to
When I was trying to save cookies from one test to another in Cypress
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With