Search code examples
cypresssession-cookies

Can I use cy.session() without calling cy.visit()?


I'm new to Cypress, so apologies, if the question is inadequate. Short description of the workflow that I'm trying to achieve:

    describe('user selects products and navigates away from page', () => {
      //1
      it('user logs in and selects products', () => {
})
      //2
      it('user proceeds to compare selected products'), => {
})
      //3
      it ('user navigates away from comparison page, then back to comparison'), => {
})  
    })

This is what the login function looks like:

    Cypress.Commands.add("openAndLogin", () => {
        cy.session('login', () => {
            cy.VisitHomePage()
            cy.get('#siteHeaderTopRight').find('button.signin-btn').should('contain.text', 'Sign In').click() 
            cy.userLogin()
        })
})

The first it-block runs fine, but the 2nd throws an error because I get stuck at some cy.session related intermittent screen and can't get to the user's product selection. I also can't use cy.visit() in the 2nd block.

So my question here is this: is it possible to use cy.session() if you're moving between pages that are dependent on your actions on the previous page? I can't call cy.visit() in each it-block in this scenario, can I?

I read somewhere that each it-block should be able to run independently, but putting the whole flow in a single it-block somehow doesn't seem right, either. Thoughts?


Solution

  • Anything you wrap in a cy.session() is cached for the duration of the run.

    That means when you call cy.openAndLogin() the first time it does all the stuff inside and caches the resulting cookies, storage, etc.

    The second time you call it, it does not repeat the code, but restores all the cached values.

    The key thing is, each test should make a call to cy.openAndLogin().

    Try adding a console.log() inside the session code, it should only show once.

    Cypress.Commands.add("openAndLogin", () => {
      cy.session('login', () => {
    
        console.log('Calling sign-in')
    
        cy.VisitHomePage()
        cy.get('#siteHeaderTopRight').find('button.signin-btn')
          .should('contain.text', 'Sign In').click() 
        cy.userLogin()
      })
    })