Cypress setCookie Command

Profile picture for user arilio666

setCookie command in cypress pretty much does what the name suggests. It sets the browser cookie.

Syntax

cy.setCookie(name, value)
cy.setCookie(name, value, options)

Arguments Used In setCookie:

  1. name: Name of the cookie to set
  2. value: Value for the cookie to set
  3. options

Options In setCookie:

  1. Log: Displays command in the command log.
  2. Domain: Used to set the domain the cookie is visible to, and the default is window.location.hostname.
  3. Expiry: Since the Unix epoch is used to set when the cookie expires, the default is 20 years from now.
  4. HttpOnly: Used to specify whether the cookie is HTTP only cookie.
  5. Path: Cookie path.
  6. Secure: Secure cookie.
  7. Timeout: Time to wait for my.setCookie() to resolve.
  8. sameSite: Cookie's SameSite value. If set should be one of lax, strict, or no_restriction.

Example

Let us try to set a cookie and assert its value to be equal to the set value of the cookie.

describe('Cookie',()=>{
    it('SetCookie',()=>{
        cy.getCookies().should('be.empty')
        cy.setCookie('session_id', '77eiincnw3ne88fsfdscvs')
        cy.getCookie('session_id').should(
          'have.property',
          'value',
          '77eiincnw3ne88fsfdscvs'
        )
        })
    }

cypress set cookie

  • So we are ensuring that the cookie is empty first and setting the cookie using the setCookie command to some random cookie value.
  • Using the have.property value, we assert the cookie value of the session_id name we assigned it to.
  • So we can see that can assert that the cookie values are identical for session_id.

Rules For Using setCookie():

  • cy.setCookie() should be chained with cy.
  • cy.setCookie() only runs assertions chained once and won't retry.
  • cy.setCookie() never times out.