I want to save a cookie value using Cypress, but unfortunately I always get undefined in the log console using this code
let cookieValue;
cy.getCookie('SOME_COOKIE')
.should('have.property', 'value')
.then((cookie) => {
cookieValue = cookie.value;
})
cy.log(cookieValue);
When I try this
let cookieValue;
cy.getCookie('SOME_COOKIE')
.should('have.property', 'value', 'Dummy value')
.then((cookie) => {
cookieValue = cookie.value;
})
cy.log(cookieValue);
I can see the actual value I want in the error message.
Cypress work asynchronously and you can't consume the cookie value as you did.
From the docs
Want to jump into the command flow and get your hands on the subject directly? No problem, simply add a .then() to your command chain. When the previous command resolves, it will call your callback function with the yielded subject as the first argument.
You should go ahead with your test code inside the then callback and not relying on the external let cookieValue assignment.
Try this
cy.getCookie('SOME_COOKIE')
.should('have.property', 'value')
.then((cookie) => {
cookieValue = cookie.value;
// YOU SHOULD CONSUME `cookieValue` here
// .. go ahead inside this `then` callback
})
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