← Back to library
Cypressauthadvancedv12+
Reuse UI login session with cy.session()
Cache a UI-based login session so the login flow runs once per spec rather than before every test.
1// cypress/support/commands.js
2Cypress.Commands.add('loginByUi', (email, password) => {
3 cy.session(
4 [email, password], // cache key — Cypress re-runs setup if this changes
5 () => {
6 cy.visit('/login');
7 cy.get('[name="email"]').type(email);
8 cy.get('[name="password"]').type(password);
9 cy.get('[type="submit"]').click();
10 cy.url().should('include', '/dashboard');
11 },
12 {
13 validate() {
14 // Re-authenticate automatically if this cookie is missing or expired
15 cy.getCookie('auth_token').should('exist');
16 },
17 cacheAcrossSpecs: true, // reuse the same session across all spec files
18 }
19 );
20});
21
22// Usage in any spec:
23// cy.loginByUi('user@test.com', 'secret');
24// cy.visit('/dashboard');#cy.session#UI login#cache#session#validate