Logging in through the form takes about three seconds. That sounds small. With eighty tests, it is four minutes of every single run, just typing the same password.
You might think: why not log in once at the start, and let the other tests use that session?
Please do not. That is exactly the trap from the last lecture. Your tests would depend on each other. Run one test alone and it fails, because nobody logged in for it.
Cypress has a proper solution: cy.session. It runs your login once, saves the result, and gives it back to the next test instead of doing the steps again.
Put it inside your login command:
Cypress.Commands.add('login', (email = 'demo@nimbus.app', password = 'secure123') => {
cy.session([email, password], () => {
cy.visit('/');
cy.get('[data-testid="email-input"]').type(email);
cy.get('[data-testid="password-input"]').type(password);
cy.get('[data-testid="login-button"]').click();
cy.get('[data-testid="welcome-message"]').should('be.visible');
});
});
Two parts to notice.
The first argument, [email, password], is the key. Cypress saves one session per key. So an admin login and a normal user login are stored separately, and an admin session can never leak into a test that expects a normal user.
The function inside is your normal login. It runs the first time only. After that, Cypress restores the saved cookies and storage instead.
Here is the important part, and it is what interviewers like to hear. Every test still starts with a clean browser, and then the saved session is applied to it. Your tests do not share one live session. They share a saved copy. So they stay independent, and you still save the minutes.
One small thing that catches everyone: cy.session does not leave you on a page. Call cy.visit() after it:
beforeEach(() => {
cy.login();
cy.visit('/');
});
Remember this: save the login, not the order of your tests. Every test must still pass on its own.
Reference: cy.session.