Bird
Raised Fist0
Cypresstesting~20 mins

cy.session() for session caching in Cypress - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Session Caching Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Cypress test using cy.session()?

Consider the following Cypress test code that uses cy.session() to cache a login session. What will be the value of loginCount after running both tests?

Cypress
let loginCount = 0;

Cypress.Commands.add('login', () => {
  loginCount++;
  cy.visit('/login');
  cy.get('#username').type('user');
  cy.get('#password').type('pass');
  cy.get('button[type=submit]').click();
});

describe('Session caching test', () => {
  beforeEach(() => {
    cy.session('user-session', () => {
      cy.login();
    });
  });

  it('Test 1', () => {
    cy.visit('/dashboard');
  });

  it('Test 2', () => {
    cy.visit('/profile');
  });
});
AloginCount is 3 because cy.login() runs once per test plus once in beforeEach
BloginCount is 2 because cy.login() runs before each test
CloginCount is 0 because cy.login() is never called
DloginCount is 1 because cy.session caches the login for both tests
Attempts:
2 left
💡 Hint

Think about how cy.session() caches the session and prevents repeated login calls.

❓ assertion
intermediate
2:00remaining
Which assertion correctly verifies that a session is cached with cy.session()?

You want to verify that the session caching works by checking that the login function is called only once. Which assertion below correctly tests this behavior?

Cypress
let loginCalls = 0;

Cypress.Commands.add('login', () => {
  loginCalls++;
  // login steps
});

describe('Session caching', () => {
  beforeEach(() => {
    cy.session('session-key', () => {
      cy.login();
    });
  });

  it('Test A', () => {
    cy.visit('/pageA');
  });

  it('Test B', () => {
    cy.visit('/pageB');
  });

  after(() => {
    // Assertion here
  });
});
Aexpect(loginCalls).to.equal(2);
Bexpect(loginCalls).to.equal(1);
Cexpect(loginCalls).to.be.lessThan(1);
Dexpect(loginCalls).to.be.greaterThan(1);
Attempts:
2 left
💡 Hint

Remember that cy.session() caches the session so the login function runs only once.

🔧 Debug
advanced
2:00remaining
Why does this cy.session() test fail to cache the session?

Look at the code below. The session caching does not work as expected and the login function runs before every test. What is the most likely cause?

Cypress
let loginCount = 0;

Cypress.Commands.add('login', () => {
  loginCount++;
  cy.visit('/login');
  cy.get('#user').type('user');
  cy.get('#pass').type('pass');
  cy.get('button').click();
});

describe('Session caching failure', () => {
  beforeEach(() => {
    cy.session(() => {
      cy.login();
    });
  });

  it('Test 1', () => {
    cy.visit('/home');
  });

  it('Test 2', () => {
    cy.visit('/settings');
  });
});
Acy.session() must be called inside each test, not beforeEach
BThe login function has a syntax error causing it to rerun
CThe session key is missing in cy.session(), so it cannot cache sessions
Dcy.visit() inside login causes session caching to fail
Attempts:
2 left
💡 Hint

Check the parameters passed to cy.session(). What is required for caching?

❓ framework
advanced
2:00remaining
How does cy.session() improve test performance in Cypress?

Which statement best explains how cy.session() improves test speed and reliability?

AIt caches browser cookies and local storage to avoid repeated login steps across tests
BIt runs all tests in parallel to reduce total execution time
CIt disables network requests during tests to speed up execution
DIt automatically retries failed tests to improve reliability
Attempts:
2 left
💡 Hint

Think about what data cy.session() saves and restores between tests.

🧠 Conceptual
expert
2:00remaining
What happens if the session validation callback in cy.session() fails?

In cy.session(), you can provide a validation callback to check if the cached session is still valid. What is the behavior if this validation callback returns false or throws an error?

AThe cached session is discarded and the setup callback runs again to create a new session
BThe test fails immediately with a session validation error
CThe cached session is used anyway without re-running setup
DThe test retries the validation callback indefinitely until it passes
Attempts:
2 left
💡 Hint

Consider what should happen if the cached session is no longer valid.

Practice

(1/5)
1. What is the main purpose of using cy.session() in Cypress tests?
easy
A. To run tests in parallel
B. To clear cookies before each test
C. To cache user sessions and avoid repeated login steps
D. To generate random test data

Solution

  1. Step 1: Understand what cy.session() does

    cy.session() caches login or setup steps so tests don't repeat them.
  2. Step 2: Identify the main benefit

    This caching speeds up tests by reusing sessions instead of logging in every time.
  3. Final Answer:

    To cache user sessions and avoid repeated login steps -> Option C
  4. Quick Check:

    Session caching = Avoid repeated logins [OK]
Hint: Remember: cy.session() saves login to speed tests [OK]
Common Mistakes:
  • Thinking it clears cookies instead of caching sessions
  • Confusing it with parallel test execution
  • Assuming it generates test data
2. Which of the following is the correct syntax to create a session with cy.session()?
easy
A. cy.session('user', () => { cy.login() })
B. cy.session('user', cy.login())
C. cy.session('user', function cy.login())
D. cy.session('user', cy.login)

Solution

  1. Step 1: Recall cy.session() syntax

    The second argument must be a callback function that runs login steps, e.g., () => { cy.login() }.
  2. Step 2: Check each option

    Only cy.session('user', () => { cy.login() }) correctly passes a callback function. The other options pass a function reference incorrectly, execute the function immediately, or use invalid syntax.
  3. Final Answer:

    cy.session('user', () => { cy.login() }) -> Option A
  4. Quick Check:

    Callback function syntax = cy.session('user', () => { cy.login() }) [OK]
Hint: Use arrow function for session callback: () => { ... } [OK]
Common Mistakes:
  • Passing function call instead of function
  • Using invalid function syntax
  • Omitting the callback wrapper
3. Given the code below, what will be the output in the test run?
cy.session('admin', () => {
  cy.visit('/login')
  cy.get('#username').type('admin')
  cy.get('#password').type('password')
  cy.get('button[type=submit]').click()
})

cy.session('admin', () => {
  cy.visit('/dashboard')
})
medium
A. The login steps run only once; second session reuses cached login
B. Both sessions run login steps twice
C. Second session throws an error because visit is different
D. The test fails due to duplicate session keys

Solution

  1. Step 1: Understand session caching behavior

    Sessions with the same key ('admin') cache the first login steps and reuse them in subsequent calls.
  2. Step 2: Analyze the second cy.session() call

    The second call with the same key skips login steps and reuses the cached session, so only the visit to '/dashboard' runs.
  3. Final Answer:

    The login steps run only once; second session reuses cached login -> Option A
  4. Quick Check:

    Same key session = cached login reused [OK]
Hint: Same session key means login runs once only [OK]
Common Mistakes:
  • Assuming login runs every time
  • Thinking different visits cause errors
  • Believing duplicate keys cause test failure
4. Identify the error in the following code using cy.session():
cy.session('user', () => {
  cy.visit('/login')
  cy.get('#user').type('test')
  cy.get('#pass').type('1234')
  cy.get('button').click()
})

cy.session('user', () => {
  cy.visit('/profile')
})
medium
A. The session key 'user' is reused, causing session cache conflict
B. The login callback does not return a promise or chain commands
C. The second session callback should include login steps again
D. No error; code works as expected

Solution

  1. Step 1: Check session key usage

    Reusing the same session key 'user' is correct to cache and reuse the session.
  2. Step 2: Verify callback structure

    The callback contains Cypress commands chained properly; no need to return a promise explicitly.
  3. Step 3: Confirm second session usage

    The second session call reuses the cached session and visits '/profile' without error.
  4. Final Answer:

    No error; code works as expected -> Option D
  5. Quick Check:

    Reusing session key with proper callback = No error [OK]
Hint: Reusing session key with proper callback is valid [OK]
Common Mistakes:
  • Thinking session keys must be unique per call
  • Expecting explicit promise return in callback
  • Assuming login steps must repeat every time
5. You want to speed up tests by caching sessions but notice some tests fail intermittently due to stale session data. How can you modify cy.session() usage to fix this?
hard
A. Use a different session key for every test to avoid caching
B. Add a validate callback to check session validity before reuse
C. Remove cy.session() and login every time
D. Clear cookies manually before each test instead of using cy.session()

Solution

  1. Step 1: Understand stale session problem

    Stale sessions cause intermittent failures because cached data may expire or become invalid.
  2. Step 2: Use validate callback in cy.session()

    The validate callback runs before reusing a session to confirm it is still valid, forcing a fresh login if needed.
  3. Step 3: Avoid other options

    Using different keys disables caching, removing benefits. Removing cy.session() slows tests. Clearing cookies manually is less efficient.
  4. Final Answer:

    Add a validate callback to check session validity before reuse -> Option B
  5. Quick Check:

    Validate callback fixes stale session issues [OK]
Hint: Use validate callback to confirm session freshness [OK]
Common Mistakes:
  • Disabling caching by changing keys unnecessarily
  • Ignoring session validation causing flaky tests
  • Removing session caching and slowing tests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard