Consider the following Cypress test code that uses cy.session() to preserve login state between tests. What will be the value of loggedIn after both tests run?
let loggedIn = false; describe('Session preservation', () => { before(() => { cy.session('user-session', () => { cy.visit('/login'); cy.get('#username').type('user'); cy.get('#password').type('pass'); cy.get('#login-button').click(); }); }); it('Test 1: sets loggedIn to true', () => { cy.visit('/dashboard'); cy.get('h1').should('contain', 'Dashboard'); loggedIn = true; }); it('Test 2: checks loggedIn value', () => { expect(loggedIn).to.equal(true); }); });
cy.session() preserves browser session state, but JavaScript variables declared outside tests persist across it blocks automatically.
In Cypress, JavaScript variables like loggedIn declared at the top level of the spec file persist across tests because the file executes in a single scope. The second test passes as loggedIn is true. Separately, cy.session() preserves browser state like cookies and localStorage.
You want to check that the cookie named auth_token is preserved between two Cypress tests. Which assertion inside the second test will correctly verify this?
Remember that cy.getCookie() returns a Cypress chainable, so assertions should be chained.
Option D correctly chains should('exist') to the Cypress command cy.getCookie(). Options A and B incorrectly use expect on a Cypress command without resolving it. Option D uses an invalid assertion.
Look at this Cypress test suite. The localStorage is set in the first test but is empty in the second test. Why?
describe('LocalStorage test', () => { it('sets localStorage item', () => { cy.visit('/'); cy.window().then((win) => { win.localStorage.setItem('token', 'abc123'); }); cy.get('#status').should('contain', 'Logged in'); }); it('checks localStorage item', () => { cy.visit('/'); cy.window().then((win) => { const token = win.localStorage.getItem('token'); expect(token).to.equal('abc123'); }); }); });
Think about how Cypress resets the browser state between tests.
Cypress clears localStorage between tests to ensure test isolation. To preserve localStorage, you must explicitly save and restore it using hooks or plugins.
To avoid logging in before every test, which Cypress command helps preserve session state automatically?
Check Cypress documentation for session management commands.
cy.session() is the official Cypress command to cache and restore session data like cookies and localStorage between tests. The other commands do not exist.
Why does Cypress clear cookies, localStorage, and sessionStorage between tests unless explicitly preserved?
Think about test best practices and why isolation matters.
Isolating tests prevents flaky tests caused by leftover state. It ensures each test starts fresh, making results more reliable and easier to debug.