sessionautomationcypresscypress-intercept

Cypress. How to restore session after the redirects?


I'm using the cy.session() for login in beforeEach section.

But Cypress clears the session on redirects, such as 3DS payment. (so in my case I'm redirected to the login page against of recipe page). I found that the Cypress behavior is like turning on the "Disable Cache" in Chrome devtools.

The main issue is that I cant restore the session using the cy.session() in exact place in the test.

The example:

  beforeEach(() => {
    cy.session('login', () => {
      cy.loginAsUser('defaultUser')
    })
  })

it('Ticket page', () => {

page.enterCreditCardData()
page.clickPayButton()
wait('@payment-done).then(()=>{

//once '@payment-done' interception is occured - the session is cleared

cy.session('login') // this returns an error: "In order to use cy.session(), provide a setup as the second argument"

cy.session('login', () => {
      page.assertThePage()
    }) // this returns an error: "This session already exists. You may not create a new session with a previously used identifier"

//at this step the session is lost because of 3DS redirects
//I need to restore the session here, but I cant because of cy.session() tries to create a new session with the same name
})
}) 

I tried to make custom commands like "saveSessionCookie" and "RestoreSessionCookies", but it didn't help


Solution

  • It seems the session can be restored in the middle of the test as long as the session signature is the same both times (in the beforeEach() and midway in the test).

    In this example I extracted the setup function to make sure the same one is used mid-test.

    const setup = () => {
      console.log('Calling session setup')
      cy.setCookie('session_id', '123key')
    }
    
    beforeEach(() => {
      cy.session('login', setup)
    })
    
    it('simple cookie check', () => {
      cy.getCookie('session_id')
        .its('value')
        .should('eq', '123key')
    })
    
    it('check cookie, clear it, and restore from session cache', () => {
      cy.getCookie('session_id')
        .its('value')
        .should('eq', '123key')
    
      cy.clearCookie('session_id')
    
      cy.getCookie('session_id')
        .should('eq', null)
    
      cy.session('login', setup)                // call session again
    
      cy.getCookie('session_id')
        .its('value')
        .should('eq', '123key')
    })
    

    enter image description here