cypress

How to use cy.session() as a replacement for Cypress.Cookies.defaults() to store a unique Id


Currently I am using Cypress.Cookies.defaults({ preserve: 'uniqueId' }); in my Cypress tests to persist a unique Id across multiple tests. However, I recently updated Cypress to version 12.9.0 and discovered that Cypress.Cookies.defaults() was deprecated in version 12.0.0 and replaced with cy.session().

How can I persist a single unique Id using cy.session()?


Solution

  • You use cy.session() in a beforeEach() hook. Any cookies set there will be preserved across tests.

    The setup function of cy.session() is responsible for setting the cookie original value.

    Setup is only called once, subsequent calls to cy.session() restore the cookie from cache.

    beforeEach(() => {
      cy.session('cookies', () => {
        cy.setCookie('session_id', '189jd09sufh33aaiidhf99d09')
        // or use a login command, cy.request(), or whatever adds the cookie
      })
    })
    
    it('Test1', () => {
      cy.getCookie('session_id')
        .should('have.property', 'value', '189jd09sufh33aaiidhf99d09')
    })
    
    it('Test2', () => {
      cy.getCookie('session_id')
        .should('have.property', 'value', '189jd09sufh33aaiidhf99d09')
    })
    

    To clarify for those who still don't get it

    Yes, it is caching the cookie - that's what cy.session() is for.

    In this sample code I use cy.setCookie(...) as a representation of code that sets the cookie, because it's makes a simple, runnable example.

    In a real test it could be set via a login command, a request, or visit where the app has set the cookie.

    The point is, you can actually run the above code and observe that the cookie has been preserved between tests.