Bird
0
0

What is wrong with this Cypress test code that tries to use a token for authorization?

medium📝 Debug Q7 of 15
Cypress - Authentication and Sessions
What is wrong with this Cypress test code that tries to use a token for authorization?
let token;

cy.request('POST', '/auth', { user: 'admin', pass: 'admin' })
  .then(res => {
    token = res.body.token;
  });

cy.request({
  method: 'GET',
  url: '/dashboard',
  headers: { Authorization: `Bearer ${token}` }
});
AToken should be stored in localStorage, not variable
BAuthorization header syntax is incorrect
CThe second request runs before token is assigned
DGET method cannot have headers
Step-by-Step Solution
Solution:
  1. Step 1: Analyze asynchronous flow

    The first request is asynchronous; the second request runs immediately without waiting for token assignment.
  2. Step 2: Understand timing issue

    Because token is undefined when the second request runs, the Authorization header is incorrect.
  3. Final Answer:

    The second request runs before token is assigned -> Option C
  4. Quick Check:

    Async timing causes token undefined [OK]
Quick Trick: Chain requests or use aliases to wait for token [OK]
Common Mistakes:
  • Assuming synchronous execution
  • Misusing header syntax
  • Thinking GET cannot have headers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes