Cypress getCookie Command

Profile picture for user arilio666

getCookie command in cypress is used to fetch a browser cookie by its name.

Syntax:

cy.getCookie(name)
cy.getCookie(name, options)

Arguments Used In getCookie:

  • Name: The name of the cookie to fetch goes here.
  • Options:
    •  Domain: Superdomain of the current URL retrieves the cookie from the specified domain
    • Log: Displays command in the command log.
    •  Timeout: Wait time for cy.getCookie() to resolve before timing out.

Proper Usage Of getCookie:

cy.getCookie('CookieName')

Example:

For example, the programsbuzz login page will be used to get a cookie and play around with it.

Here is the list of cookies for the page and its properties with them. let's play around with _gat and _gcl_au cookies.

describe('getCookie Command',() => {
   it('Visit Page',() => {
       cy.visit("https://www.programsbuzz.com/user/login")
       cy.getCookie('_gat').should('have.property','value','1')
       cy.getCookie('_gcl_au').then((cookie) => {
           expect(cookie).to.have.property('domain')
           expect(cookie).to.have.property('domain','.programsbuzz.com')

       })
 
Using _gat cookie, we are asserting property value to be 1.
With _gcl_au, the cookie, we expect property and value to be 'domain' and '.programsbuzz.com'.
  • We can see that it has been asserted successfully.

This shows the cookies _gat and _gcl_au we fetched, along with their various properties and value.

Yield Of getCookie:

  • getCookie yields domain, expiry, httpOnly, name, path, value, sameSite, and secure.
  • When cy.getCookie() cannot find a matching or specified name, it yields null.