Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cypress session redirects to blank page

I am new to cypress and perhaps missing some key understanding in how sessions work within cypress.

I am building a simple test that will do a login in to the system and then perform a certain action Bellow is my test. The login function performs as expected, but when the first it finishes the sequence goes to a blank page and unless I do another login in the next it it doesn't work. How can I persist the session between different its and not have it jump pages?

describe('create cycle', () =>{

    it("login as super user", () =>{
    cy.session('login', ()=>{
            cy.visit('/')
            login();
        })  
    })

    it('start cycle', ()=>{  
      cy.get("#cycles-library > ul > #library-item-2").click();
      cy.get("#create-cycle").click()
      cy.get("#startDate > label").first().click()
      cy.get("#duration > label").first().click()
      cy.get('#groups-input').click()
      cy.get("body>div").last().contains('group 2').click()
      cy.get("button#create-cycle").click()

    })

})

Thanks!

like image 858
arthur Avatar asked Sep 10 '25 18:09

arthur


2 Answers

cy.session() generally works with beforeEach() to ensure proper session data is set for each test.

The pattern is

describe('tests requiring session data', () =>{

  beforeEach(() =>{
    cy.session('login', ()=>{
      cy.visit('/')
      login();
    })  
  })

  it('test that expects logged-in status', () => {  

  it('another one', () => {  
})

It may appear that you are performing the login each time, but it's not so. The cy.session() is a caching function, it runs once on the first test then just restores the session data for each subsequent test.

You can think of it like React hooks useEffect() with an empty dependency list, which also runs just once in the component lifecycle.

Since you also have a test for logging in, you should perform that separately in another describe() block, since the initial conditions are different for each test.

In my case, I had to set the testIsolation property to false. After that cy.session started to work and not ending with a blank page:

describe('my tests',{ testIsolation: false }, () => {...});
like image 37
Sebastian Denis Avatar answered Sep 13 '25 08:09

Sebastian Denis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!