HNhu
HNhu

Reputation: 137

Cypress - How to Get Cookies with cypress version 10

I am using cypress version 10.7.0 but I using getCookie of previous version

Here my code in command.js

afterEach(() => {
    let str = [];
    cy.getCookies().then((cook) => {
        cy.log(cook);
        for (let l = 0; l < cook.length; l++) {
            str[l] = cook[l].name;
            Cypress.Cookies.preserveOnce(str[l]); 
        }
    })
})

It run well but sometimes Fail and dislay error as image
enter image description here

Upvotes: 2

Views: 708

Answers (2)

HNhu
HNhu

Reputation: 137

Now my Cypress version is 12.7.0

I try testIsolation: false in cypress.config.js

module.exports = defineConfig({
  e2e: {
    watchForFileChanges: false,
    defaultCommandTimeout: 5000,
    testIsolation: false,
    baseUrl: '',
    setupNodeEvents(on, config) {
    },
  }
});

And I clear cookie and clearAllLocalStorage in before

It's work.

Upvotes: 1

Mike G
Mike G

Reputation: 174

There is a custom command here cypress-v10-preserve-cookie that may work better.

The only thing that's different is you must know the names of the cookies, but you should already know that.

Cypress.Commands.add('preserveCookieOnce', (...names) => {
  if (!names.length) {
    throw new Error('Expected at least one cookie name')
  }

  names.forEach((name) => {
    if (typeof name !== 'string' || !name) {
      throw new Error('Expected the cookie name to preserve')
    }
    cy.log(`preserveCookieOnce **${name}**`)
    const saveName = 'cookie_' + name
    cy.getCookie(name, { log: false })
      // disable the built-in existence check
      .should(Cypress._.noop)
      .then((c) => {
        if (!c) {

          cy.log('there is no cookie named %s', name)

          const previouslySaved = Cypress.env(saveName)
          if (previouslySaved) {
            debug(
              'setting the previously saved cookie %s %o',
              name,
              previouslySaved,
            )
            cy.setCookie(name, previouslySaved.value, { log: false })
          }
        } else {
          Cypress.env(saveName, c)
        }
      })
  })
})

I changed the debug() to cy.log() to show if cookie value has gone, it seems you have this problem occasionally.

Upvotes: 3

Related Questions