ounis
ounis

Reputation: 43

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.

Upvotes: 4

Views: 6585

Answers (2)

Puneet Punj
Puneet Punj

Reputation: 11

you can also use Async and await instead of adding code inside then()

const getmyCookie = async (cookiename) => {
    return cy.getCookie(cookiename)
        .should('exist')
        .then(async (c) => {
            cy.log(c.value)
            return c.value
        })
}

Use it in your test and ensure your it block is async

it('Sample Test', async function () {
   ... some code

   const cookie = await getmyCookie('cookiename')
   cy.log(cookie)

   ... some code
})

Upvotes: 0

NoriSte
NoriSte

Reputation: 3709

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
    })

Upvotes: 7

Related Questions