Bird
0
0

You want to create a reusable Cypress command for programmatic login that stores the token and sets it as a cookie for later tests. Which code snippet correctly achieves this?

hard📝 framework Q15 of 15
Cypress - Authentication and Sessions
You want to create a reusable Cypress command for programmatic login that stores the token and sets it as a cookie for later tests. Which code snippet correctly achieves this?
ACypress.Commands.add('login', () => { cy.request('GET', '/api/login') .then((res) => { cy.setCookie('authToken', res.body.token) }) })
BCypress.Commands.add('login', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() })
CCypress.Commands.add('login', () => { cy.request('POST', '/api/login', { username: 'user', password: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) })
DCypress.Commands.add('login', () => { cy.request('POST', '/api/login', { user: 'user', pass: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) })
Step-by-Step Solution
Solution:
  1. Step 1: Check HTTP method and payload correctness

    Login usually requires POST with correct keys; Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { username: 'user', password: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) }) uses 'username' and 'password' correctly.
  2. Step 2: Verify token storage and cookie setting

    Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { username: 'user', password: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) }) sets the cookie 'authToken' with the token from response body, enabling session reuse.
  3. Step 3: Review other options for errors

    Cypress.Commands.add('login', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() }) uses UI login, not programmatic. Cypress.Commands.add('login', () => { cy.request('GET', '/api/login') .then((res) => { cy.setCookie('authToken', res.body.token) }) }) uses GET instead of POST. Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { user: 'user', pass: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) }) uses wrong keys 'user' and 'pass'.
  4. Final Answer:

    Reusable command with POST request, correct keys, and cookie set. -> Option C
  5. Quick Check:

    POST + correct keys + setCookie = reusable login [OK]
Quick Trick: Use POST with correct keys and setCookie for token [OK]
Common Mistakes:
  • Using GET instead of POST for login
  • Wrong payload keys like 'user' instead of 'username'
  • Trying UI login instead of programmatic
  • Not setting cookie after login

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes