Cookies

Examples of managing cookies in Cypress, for a full reference of commands, go to docs.cypress.ioopen in new window

cy.getCookie()open in new window

To get a browser cookie, use the cy.getCookie() command.

<div id="getCookie">
  <button class="set-a-cookie btn btn-success">
    Set Cookie
  </button>
</div>
<script>
  $('.set-a-cookie').on('click', function (e) {
    e.preventDefault()
    document.cookie = 'token=123ABC'
  })
</script>
cy.clearCookies()

cy.get('#getCookie .set-a-cookie').click()

// cy.getCookie() yields a cookie object
cy.getCookie('token').should('have.property', 'value', '123ABC')

cy.getCookies()open in new window

To get all browser cookies, use the cy.getCookies() command.

<div id="getCookies">
  <button class="set-a-cookie btn btn-success">
    Set Cookie
  </button>
</div>
<script>
  $('.set-a-cookie').on('click', function (e) {
    e.preventDefault()
    document.cookie = 'token=123ABC'
  })
</script>
cy.clearCookies()
cy.getCookies().should('be.empty')

cy.get('#getCookies .set-a-cookie').click()

// cy.getCookies() yields an array of cookies
cy.getCookies()
  .should('have.length', 1)
  .its(0)
  .should('include', {
    name: 'token',
    value: '123ABC',
    httpOnly: false,
    secure: false,
  })
  // there are also other properties in the cookie object
  .and('include.keys', ['domain', 'path'])

cy.setCookie()open in new window

To set a browser cookie, use the cy.setCookie() command.

cy.clearCookies()
cy.getCookies().should('be.empty')

cy.setCookie('foo', 'bar')

// cy.getCookie() yields a cookie object
cy.getCookie('foo').should('have.property', 'value', 'bar')

cy.clearCookie()open in new window

To clear a browser cookie, use the cy.clearCookie() command.

<div id="clearCookie">
  <button class="set-a-cookie btn btn-success">
    Set Cookie
  </button>
</div>
<script>
  $('.set-a-cookie').on('click', function (e) {
    e.preventDefault()
    document.cookie = 'token=123ABC'
  })
</script>
cy.clearCookies()
cy.getCookie('token').should('be.null')

cy.get('#clearCookie .set-a-cookie').click()

cy.getCookie('token').should('have.property', 'value', '123ABC')

// cy.clearCookies() yields null
cy.clearCookie('token').should('be.null')

cy.getCookie('token').should('be.null')

cy.clearCookies()open in new window

To clear all browser cookies, use the cy.clearCookies() command.

<div id="clearCookies">
  <button class="set-a-cookie btn btn-success">
    Set Cookie
  </button>
</div>
<script>
  $('.set-a-cookie').on('click', function (e) {
    e.preventDefault()
    document.cookie = 'token=123ABC'
  })
</script>
cy.clearCookies()
cy.getCookies().should('be.empty')

cy.get('#clearCookies .set-a-cookie').click()

cy.getCookies().should('have.length', 1)

// cy.clearCookies() yields null
cy.clearCookies()

cy.getCookies().should('be.empty')