Bird
Raised Fist0
Cypresstesting~20 mins

Token-based authentication in Cypress - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Token Auth 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 snippet?

Consider this Cypress test that tries to authenticate using a token and then checks the user profile page.

describe('Token Auth Test', () => {
  it('should load profile with valid token', () => {
    cy.visit('/profile', {
      onBeforeLoad(win) {
        win.localStorage.setItem('authToken', 'valid-token-123')
      }
    })
    cy.get('[data-cy=user-name]').should('contain.text', 'Alice')
  })
})

What will happen when this test runs?

Cypress
describe('Token Auth Test', () => {
  it('should load profile with valid token', () => {
    cy.visit('/profile', {
      onBeforeLoad(win) {
        win.localStorage.setItem('authToken', 'valid-token-123')
      }
    })
    cy.get('[data-cy=user-name]').should('contain.text', 'Alice')
  })
})
ATest fails because cy.get selector is incorrect and throws an error
BTest fails because localStorage cannot be set in onBeforeLoad
CTest passes because the token is set before page load and user name is found
DTest passes but assertion fails because user name is not 'Alice'
Attempts:
2 left
💡 Hint

Think about when localStorage is set and how Cypress commands work.

❓ assertion
intermediate
1:30remaining
Which assertion correctly verifies the token is stored in localStorage?

You want to check that the token 'abc123' is saved in localStorage under the key 'authToken' after login.

Which Cypress assertion is correct?

Cypress
cy.window().then(win => {
  // assertion here
})
Aexpect(win.localStorage.authToken).to.equal('abc123')
Bexpect(win.localStorage.getItem('authToken')).to.equal('abc123')
Cexpect(win.localStorage.getItem('authToken')).to.be.undefined
Dexpect(win.localStorage.authToken).to.be.true
Attempts:
2 left
💡 Hint

Remember how to get an item from localStorage and check its value.

❓ locator
advanced
1:30remaining
Which locator is best practice to select the login button for token authentication?

You want to select the login button in your Cypress test to trigger token-based login.

Which locator is best for maintainability and accessibility?

Acy.get('button.login')
Bcy.get('#loginBtn')
Ccy.get('button').contains('Login')
Dcy.get('[data-cy=login-button]')
Attempts:
2 left
💡 Hint

Think about selectors that are stable and do not depend on styling or text.

🔧 Debug
advanced
2:00remaining
Why does this Cypress test fail to authenticate with token?

Look at this test code snippet:

cy.visit('/dashboard')
cy.window().then(win => {
  win.localStorage.setItem('authToken', 'token123')
})
cy.get('[data-cy=welcome-msg]').should('contain.text', 'Welcome')

Why does the test fail to show the welcome message?

AThe token is set after the page loads, so the app does not see it on initial load
BlocalStorage.setItem syntax is incorrect and throws an error
CThe selector '[data-cy=welcome-msg]' is invalid and causes failure
DThe token value 'token123' is expired and rejected by the app
Attempts:
2 left
💡 Hint

Consider when localStorage is set relative to page load.

❓ framework
expert
3:00remaining
How to securely handle token refresh in Cypress tests?

Your app uses short-lived tokens and refresh tokens to maintain authentication.

Which approach is best to handle token refresh automatically in Cypress tests?

AUse Cypress task to call backend refresh endpoint and update tokens dynamically
BIntercept API calls and stub token refresh responses with fixed tokens
CManually set new tokens in localStorage before each test without API calls
DIgnore token refresh and rely on long-lived tokens for tests
Attempts:
2 left
💡 Hint

Think about how to keep tokens fresh and tests realistic.

Practice

(1/5)
1. What is the main advantage of using token-based authentication in Cypress tests?
easy
A. It disables all API requests during testing.
B. It requires manual input of username and password every time.
C. It automatically generates UI elements for login.
D. It allows tests to log in quickly without interacting with the UI.

Solution

  1. Step 1: Understand token-based authentication purpose

    Token-based authentication lets tests bypass UI login by using tokens directly.
  2. Step 2: Compare options

    Only It allows tests to log in quickly without interacting with the UI. correctly states the advantage of faster login without UI interaction.
  3. Final Answer:

    It allows tests to log in quickly without interacting with the UI. -> Option D
  4. Quick Check:

    Token-based authentication = Fast login without UI [OK]
Hint: Token-based auth skips UI login for faster tests [OK]
Common Mistakes:
  • Thinking token auth requires UI interaction
  • Confusing token auth with disabling APIs
  • Assuming token auth auto-generates UI
2. Which Cypress command is commonly used to request an authentication token from an API?
easy
A. cy.visit()
B. cy.get()
C. cy.request()
D. cy.contains()

Solution

  1. Step 1: Identify command for API calls

    cy.request() is used to make HTTP requests to APIs, including login endpoints.
  2. Step 2: Eliminate other commands

    cy.visit() loads pages, cy.get() selects DOM elements, cy.contains() finds text; none request tokens.
  3. Final Answer:

    cy.request() -> Option C
  4. Quick Check:

    API token request = cy.request() [OK]
Hint: Use cy.request() to call APIs and get tokens [OK]
Common Mistakes:
  • Using cy.visit() to get tokens
  • Confusing cy.get() with API calls
  • Trying cy.contains() for authentication
3. Given the code below, what will be the value of token after the test runs?
let token = '';
cy.request('POST', '/api/login', { username: 'user', password: 'pass' })
  .then((response) => {
    token = response.body.token;
  });
medium
A. An empty string because token is declared outside the callback
B. The token string returned by the API in response.body.token
C. Undefined because response.body.token does not exist
D. The entire response object

Solution

  1. Step 1: Understand asynchronous assignment

    The token variable is assigned inside the .then() callback after the API response arrives.
  2. Step 2: Confirm token value after request

    response.body.token contains the token string from the API, so token gets that value.
  3. Final Answer:

    The token string returned by the API in response.body.token -> Option B
  4. Quick Check:

    token = response.body.token string [OK]
Hint: Token is set inside .then() from response.body.token [OK]
Common Mistakes:
  • Assuming token stays empty due to async
  • Thinking token is undefined without checking API
  • Confusing token with full response object
4. Identify the error in this Cypress test snippet for token-based login:
cy.request('POST', '/api/login', { username: 'user', password: 'pass' })
  .then((response) => {
    cy.setCookie('authToken', response.token);
  });
medium
A. response.token should be response.body.token to access the token
B. cy.setCookie is not a valid Cypress command
C. The request method should be GET, not POST
D. Cookies cannot store authentication tokens

Solution

  1. Step 1: Check response object structure

    The token is usually inside response.body.token, not directly response.token.
  2. Step 2: Validate cy.setCookie usage

    cy.setCookie is a valid command to set cookies in Cypress.
  3. Final Answer:

    response.token should be response.body.token to access the token -> Option A
  4. Quick Check:

    Access token via response.body.token [OK]
Hint: Use response.body.token, not response.token [OK]
Common Mistakes:
  • Using response.token instead of response.body.token
  • Thinking cy.setCookie is invalid
  • Changing POST to GET incorrectly
5. You want to write a Cypress test that logs in using token-based authentication and then visits a protected page. Which sequence correctly achieves this?
A) cy.request('POST', '/api/login', {username: 'user', password: 'pass'}).then(res => {
  cy.setCookie('token', res.token);
});
cy.visit('/protected');

B) cy.visit('/protected');
cy.request('POST', '/api/login', {username: 'user', password: 'pass'}).then(res => {
  cy.setCookie('token', res.body.token);
});

C) cy.request('POST', '/api/login', {username: 'user', password: 'pass'}).then(res => {
  cy.setCookie('token', res.body.token);
  cy.visit('/protected');
});

D) cy.setCookie('token', 'dummy');
cy.visit('/protected');
hard
A. Set dummy token cookie, then visit protected page
B. Visit protected page first, then request token and set cookie
C. Request token, set cookie, then visit protected page outside .then()
D. Request token, set cookie, then visit protected page inside .then() callback

Solution

  1. Step 1: Understand asynchronous flow

    Token must be set before visiting the protected page, so visit must happen after setting cookie inside .then().
  2. Step 2: Analyze options

    Request token, set cookie, then visit protected page inside .then() callback sets cookie and visits page inside .then(), ensuring correct order and token availability.
  3. Final Answer:

    Request token, set cookie, then visit protected page inside .then() callback -> Option A
  4. Quick Check:

    Set token cookie before visiting page inside .then() [OK]
Hint: Visit protected page only after setting token cookie inside .then() [OK]
Common Mistakes:
  • Visiting page before setting token cookie
  • Setting cookie outside async callback
  • Using dummy tokens without real login
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