Search code examples
cypress

Cypress: Log-in for one test and stay logged-in for the next test


I would like to know if there is a way to log in within one it() and be able to stay logged in for the next it()

As an example:

it('logs in', () =>{
    cy.login('username', 'password');// This calls a custom command
})

it('next step', () =>{
    cy.get('div.nextStep').click();
})

I know I can use before() to log in and then beforeEach() and capture the cookie, and this way, the session persists, but I want to log in inside an it() and the user stays logged in for the test in the next it(), is this possible?


Solution

  • To do that in Cypress 12, turn off testIsolation.

    Test Isolation Disabled

    When test isolation is disabled, Cypress will not alter the browser context before the test starts. The page does not clear between tests and cookies, local storage and session storage will be available across tests in that suite. Additionally, the cy.session() command will only clear the current browser context when establishing the browser session - the current page is not cleared.

    cypress.config.js

    const { defineConfig } = require('cypress')
    
    module.exports = defineConfig({
      e2e: {
        baseUrl: 'http://localhost:1234',
        testIsolation: false,
      },
    })
    

    I've highlighted the part that is important for cy.login(). Keeping the artifacts of the login process will enable the second test to pass.