Cypress · Browser testing end to end
How does cy.session work and when should you use it?
Short answer
cy.session caches cookies, local storage and session storage under an identifier, runs the setup once, and restores that state for later tests. Use it for login and other expensive setup that must persist.
cy.session takes an identifier and a setup function. The first call runs the setup and saves the resulting browser state. Later calls with the same identifier restore the saved state instead of re-running the setup. It is the supported way to reuse authentication while keeping test isolation.
beforeEach(() => {
cy.session(["asha", "admin"], () => {
cy.request({
method: "POST",
url: "/api/auth/login",
body: { email: "asha@example.com", password: "secret123" },
}).then((response) => {
cy.setCookie("session", response.body.token);
});
cy.visit("/dashboard");
cy.location("pathname").should("eq", "/dashboard");
});
});Options and behaviour
- The identifier can be a string or a serialisable array such as a user and role
- validate runs before restoring a cached session and can force a fresh setup
- cacheAcrossSpecs reuses the session across spec files in the same run
- The setup function should include an assertion that the session works
- A session does not seed backend data; it only restores browser state
cy.session("admin", () => {
cy.loginByApi("admin@example.com", "secret123");
}, {
cacheAcrossSpecs: true,
validate() {
cy.request("/api/auth/me").its("status").should("eq", 200);
},
});Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What browser state does cy.session cache?
- 2When would you use the validate option?
- 3What does cacheAcrossSpecs change?
- 4Why must the setup function assert success?
Say it in the interview
cy.session caches cookies and web storage under an identifier. The first call runs the setup and later calls restore the saved state. I use it for login and other expensive setup, and I always assert inside the setup that the session actually works. I add validate when a cached session might expire, and cacheAcrossSpecs when the same login is reused across spec files.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Cypress mock interview and get scored feedback on depth, clarity and confidence.