Bird
Raised Fist0
Cypresstesting~20 mins

Preserving state between tests in Cypress - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
State Preservation 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 code?

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?

Cypress
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);
  });
});
AThe second test fails with a ReferenceError for loggedIn.
BThe second test fails because loggedIn is false.
CThe second test passes because loggedIn is true.
DThe second test passes but loggedIn is undefined.
Attempts:
2 left
💡 Hint

cy.session() preserves browser session state, but JavaScript variables declared outside tests persist across it blocks automatically.

❓ assertion
intermediate
1:30remaining
Which assertion correctly verifies that a cookie is preserved between tests?

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?

Aexpect(cy.getCookie('auth_token')).to.have.property('value');
Bexpect(cy.getCookie('auth_token')).to.exist;
Ccy.getCookie('auth_token').should('have.value');
Dcy.getCookie('auth_token').should('exist');
Attempts:
2 left
💡 Hint

Remember that cy.getCookie() returns a Cypress chainable, so assertions should be chained.

🔧 Debug
advanced
2:30remaining
Why does this Cypress test fail to preserve localStorage between tests?

Look at this Cypress test suite. The localStorage is set in the first test but is empty in the second test. Why?

Cypress
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');
    });
  });
});
AlocalStorage is cleared between tests by Cypress, so the second test sees empty localStorage.
BlocalStorage.setItem() is asynchronous and not awaited, so the item is not saved.
ClocalStorage is not accessible in Cypress tests due to security restrictions.
DThe second test runs before the first test, so localStorage is empty.
Attempts:
2 left
💡 Hint

Think about how Cypress resets the browser state between tests.

❓ framework
advanced
1:30remaining
Which Cypress command is designed to preserve state like cookies and localStorage between tests?

To avoid logging in before every test, which Cypress command helps preserve session state automatically?

Acy.preserve()
Bcy.session()
Ccy.cache()
Dcy.keepState()
Attempts:
2 left
💡 Hint

Check Cypress documentation for session management commands.

🧠 Conceptual
expert
2:00remaining
What is the main reason Cypress isolates state between tests by default?

Why does Cypress clear cookies, localStorage, and sessionStorage between tests unless explicitly preserved?

ATo ensure tests are independent and do not affect each other, improving reliability.
BTo speed up test execution by clearing browser data.
CBecause Cypress cannot access browser storage across tests due to security policies.
DTo force developers to write longer tests that include login steps every time.
Attempts:
2 left
💡 Hint

Think about test best practices and why isolation matters.

Practice

(1/5)
1. What is the main reason to preserve state between tests in Cypress?
easy
A. To clear all cookies after each test
B. To make tests dependent on each other
C. To avoid repeating login steps and speed up test execution
D. To disable assertions in tests

Solution

  1. Step 1: Understand test state preservation

    Preserving state means keeping some data like cookies so tests don't repeat setup steps.
  2. Step 2: Identify the benefit

    Keeping state avoids repeating login or setup, making tests faster and more efficient.
  3. Final Answer:

    To avoid repeating login steps and speed up test execution -> Option C
  4. Quick Check:

    Preserving state = faster tests [OK]
Hint: Preserve state to skip repeated steps and save time [OK]
Common Mistakes:
  • Thinking tests should be dependent on each other
  • Believing preserving state clears cookies
  • Assuming preserving state disables assertions
2. Which of the following is the correct syntax to preserve a cookie named 'session_id' only once in Cypress?
easy
A. Cypress.Cookies.preserveOnce('session_id')
B. cy.preserveCookie('session_id')
C. Cypress.preserveCookieOnce('session_id')
D. cy.Cookies.preserve('session_id')

Solution

  1. Step 1: Recall Cypress cookie preservation method

    The correct method to preserve cookies once is Cypress.Cookies.preserveOnce.
  2. Step 2: Match method and argument

    The method takes the cookie name as a string argument, e.g., 'session_id'.
  3. Final Answer:

    Cypress.Cookies.preserveOnce('session_id') -> Option A
  4. Quick Check:

    Preserve once = Cypress.Cookies.preserveOnce [OK]
Hint: Use Cypress.Cookies.preserveOnce('cookieName') to keep cookies once [OK]
Common Mistakes:
  • Using cy.preserveCookie which does not exist
  • Mixing method names like preserveCookieOnce
  • Calling preserve on cy.Cookies which is invalid
3. Given the following Cypress test code, what will be the output of the second test?
describe('Test Suite', () => {
  beforeEach(() => {
    Cypress.Cookies.preserveOnce('token')
  })

  it('Test 1: Set cookie', () => {
    cy.setCookie('token', 'abc123')
  })

  it('Test 2: Check cookie', () => {
    cy.getCookie('token').should('have.property', 'value', 'abc123')
  })
})
medium
A. Test 2 passes because the 'token' cookie is preserved
B. Test 2 fails because cookies are cleared between tests
C. Test 2 throws a syntax error
D. Test 2 passes but the cookie value is empty

Solution

  1. Step 1: Analyze cookie preservation in beforeEach

    The beforeEach hook preserves the 'token' cookie between tests using Cypress.Cookies.preserveOnce('token').
  2. Step 2: Understand cookie setting and checking

    Test 1 sets the cookie 'token' to 'abc123'. Test 2 checks the cookie value. Since the cookie is preserved, the check passes.
  3. Final Answer:

    Test 2 fails because cookies are cleared between tests -> Option B
  4. Quick Check:

    PreserveOnce keeps cookie for next test [OK]
Hint: Preserve cookie in beforeEach to keep it for next test [OK]
Common Mistakes:
  • Assuming cookies clear automatically between tests
  • Thinking preserveOnce clears cookies
  • Confusing syntax causing errors
4. You wrote this code to preserve cookies but the second test fails because the cookie is missing:
beforeEach(() => {
  Cypress.Cookies.preserveOnce('auth_token')
})

it('Login test', () => {
  cy.setCookie('auth_token', 'xyz789')
})

it('Dashboard test', () => {
  cy.getCookie('auth_token').should('exist')
})

What is the likely cause of the failure?
medium
A. The cookie is set after the beforeEach hook runs, so it is not preserved
B. The cookie name is misspelled in preserveOnce
C. Cypress cannot preserve cookies between tests
D. The assertion syntax is incorrect

Solution

  1. Step 1: Understand when preserveOnce runs

    The beforeEach hook runs before each test, so it preserves cookies existing before the test starts.
  2. Step 2: Analyze cookie setting timing

    The cookie is set inside the first test, after beforeEach runs, so it is not preserved for the next test.
  3. Final Answer:

    The cookie is set after the beforeEach hook runs, so it is not preserved -> Option A
  4. Quick Check:

    PreserveOnce must run after cookie set [OK]
Hint: Set cookies before preserveOnce runs to keep them [OK]
Common Mistakes:
  • Thinking preserveOnce preserves cookies set during the test
  • Assuming Cypress can't preserve cookies
  • Blaming assertion syntax instead of timing
5. You want to preserve multiple cookies named 'token' and 'user_id' across all tests without calling preserveOnce in every test. Which is the best way to do this in Cypress?
hard
A. Disable cookie clearing globally with Cypress.config
B. Call Cypress.Cookies.preserveOnce('token', 'user_id') in each test
C. Set cookies again in every test manually
D. Use Cypress.Cookies.defaults({ whitelist: ['token', 'user_id'] }) in support file

Solution

  1. Step 1: Understand preserving multiple cookies globally

    Using Cypress.Cookies.defaults with a preserve array keeps specified cookies across all tests automatically.
  2. Step 2: Compare with other options

    Calling preserveOnce in every test is repetitive. Manually setting cookies each time is inefficient. Disabling cookie clearing globally is not recommended.
  3. Final Answer:

    Use Cypress.Cookies.defaults({ whitelist: ['token', 'user_id'] }) in support file -> Option D
  4. Quick Check:

    Defaults preserve multiple cookies globally [OK]
Hint: Use Cypress.Cookies.defaults to preserve cookies globally [OK]
Common Mistakes:
  • Calling preserveOnce repeatedly instead of defaults
  • Manually resetting cookies each test
  • Trying to disable cookie clearing globally
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