Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress save cookie value

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.

like image 300
ounis Avatar asked Oct 23 '25 09:10

ounis


1 Answers

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
    })
like image 121
NoriSte Avatar answered Oct 25 '25 23:10

NoriSte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!