Bird
Raised Fist0
Cypresstesting~20 mins

Programmatic login (cy.request) in Cypress - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Programmatic Login Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the result of this Cypress test code?

Consider this Cypress test snippet that uses cy.request for programmatic login:

cy.request({
  method: 'POST',
  url: '/api/login',
  body: { username: 'user1', password: 'pass123' }
}).then((response) => {
  expect(response.status).to.eq(200)
  cy.setCookie('session_id', response.body.sessionId)
})
cy.visit('/dashboard')
cy.get('h1').should('contain.text', 'Welcome user1')

What will happen when this test runs?

Cypress
cy.request({
  method: 'POST',
  url: '/api/login',
  body: { username: 'user1', password: 'pass123' }
}).then((response) => {
  expect(response.status).to.eq(200)
  cy.setCookie('session_id', response.body.sessionId)
})
cy.visit('/dashboard')
cy.get('h1').should('contain.text', 'Welcome user1')
AThe test fails because cy.visit runs before the login request completes, so the dashboard is not authenticated.
BThe test passes because cy.request waits for the login to complete before visiting the dashboard.
CThe test fails because cy.setCookie is not a valid Cypress command.
DThe test passes but the assertion on the h1 text is skipped.
Attempts:
2 left
💡 Hint

Think about how Cypress commands are queued and asynchronous behavior.

❓ assertion
intermediate
1:30remaining
Which assertion correctly verifies a successful login response?

You receive this JSON response from a login API:

{"status": "success", "token": "abc123", "user": {"id": 5, "name": "Alice"}}

Which Cypress assertion correctly checks the response indicates success and contains a token?

Aexpect(response.status).to.eq(200) && expect(response.body.token).to.be.undefined
Bexpect(response.body.status).to.be.true && expect(response.body.token).to.be.a('string')
Cexpect(response.body.status).to.equal('success') && expect(response.body.token).to.exist
Dexpect(response.body.status).to.eq('success') && expect(response.body.token).to.be.a('string')
Attempts:
2 left
💡 Hint

Check the exact property names and types in the response body.

❓ locator
advanced
1:30remaining
Choose the best locator to verify login success message after programmatic login

After a successful programmatic login, the page shows a message:

<div role="alert" aria-live="polite" class="login-message">Login successful!</div>

Which Cypress selector is best to locate this message for assertion?

Acy.get('div.login-message')
Bcy.get('.login-message[role="alert"]')
Ccy.get('[aria-live="polite"]')
Dcy.get('div').contains('Login successful!')
Attempts:
2 left
💡 Hint

Consider accessibility and specificity for reliable selectors.

🔧 Debug
advanced
2:00remaining
Why does this programmatic login test fail intermittently?

Test code snippet:

cy.request('POST', '/api/login', { username: 'user', password: 'pass' })
  .then((res) => {
    cy.setCookie('auth_token', res.body.token)
  })
cy.visit('/profile')
cy.get('.profile-name').should('be.visible')

Sometimes the test fails because the profile name is not visible. Why?

Cypress
cy.request('POST', '/api/login', { username: 'user', password: 'pass' })
  .then((res) => {
    cy.setCookie('auth_token', res.body.token)
  })
cy.visit('/profile')
cy.get('.profile-name').should('be.visible')
Acy.visit runs before the cookie is set, so the profile page loads without authentication.
Bcy.setCookie is asynchronous and must be awaited with async/await syntax.
CThe selector '.profile-name' is incorrect and does not match any element.
DThe login API sometimes returns an invalid token causing the failure.
Attempts:
2 left
💡 Hint

Think about the order of Cypress commands and their execution.

❓ framework
expert
2:30remaining
Which Cypress command sequence correctly performs programmatic login and visits a protected page?

You want to programmatically log in by sending a POST request, set the auth cookie, then visit the dashboard page. Which code snippet achieves this correctly?

A
cy.visit('/dashboard')
cy.request('POST', '/api/login', {user: 'u', pass: 'p'}).then(res =&amp;gt; {
  cy.setCookie('auth', res.body.token)
})
B
cy.request('POST', '/api/login', {user: 'u', pass: 'p'}).then(res =&amp;gt; {
  cy.setCookie('auth', res.body.token)
})
cy.visit('/dashboard')
C
cy.request('POST', '/api/login', {user: 'u', pass: 'p'}).then(res =&amp;gt; {
  cy.setCookie('auth', res.body.token)
  cy.visit('/dashboard')
})
D
cy.request('POST', '/api/login', {user: 'u', pass: 'p'})
cy.setCookie('auth', 'token')
cy.visit('/dashboard')
Attempts:
2 left
💡 Hint

Remember to chain commands so they run in the correct order.

Practice

(1/5)
1. What is the main benefit of using cy.request for programmatic login in Cypress?
easy
A. It logs in faster by skipping the UI steps.
B. It visually shows the login process in the browser.
C. It requires manual input of username and password each time.
D. It disables cookies to improve security.

Solution

  1. Step 1: Understand what cy.request does

    cy.request sends HTTP requests directly without interacting with the UI.
  2. Step 2: Identify the benefit in login context

    By using cy.request for login, tests skip slow UI steps and run faster.
  3. Final Answer:

    It logs in faster by skipping the UI steps. -> Option A
  4. Quick Check:

    Programmatic login = faster login without UI [OK]
Hint: Programmatic login skips UI, making tests faster [OK]
Common Mistakes:
  • Thinking cy.request shows UI login
  • Assuming manual input is needed every time
  • Believing cookies are disabled automatically
2. Which of the following is the correct syntax to perform a POST login request using cy.request in Cypress?
easy
A. cy.request('GET', '/login', { username: 'user', password: 'pass' })
B. cy.request('/login', 'POST', { username: 'user', password: 'pass' })
C. cy.request({ url: '/login', method: 'GET', body: { username: 'user', password: 'pass' } })
D. cy.request('POST', '/login', { username: 'user', password: 'pass' })

Solution

  1. Step 1: Recall cy.request method signature

    The correct order is cy.request(method, url, body) for POST requests.
  2. Step 2: Check each option

    cy.request('POST', '/login', { username: 'user', password: 'pass' }) matches the correct syntax with method 'POST', URL '/login', and body object.
  3. Final Answer:

    cy.request('POST', '/login', { username: 'user', password: 'pass' }) -> Option D
  4. Quick Check:

    Method first, then URL, then body [OK]
Hint: Remember: method, URL, then body in cy.request [OK]
Common Mistakes:
  • Swapping method and URL order
  • Using GET instead of POST for login
  • Passing body with GET method
3. Given the following code snippet, what will be the value of token after the test runs?
cy.request('POST', '/api/login', { username: 'test', password: '1234' })
  .then((response) => {
    const token = response.body.token
    cy.wrap(token).as('authToken')
  })
medium
A. Undefined, because token is declared inside the callback only.
B. The token string returned from the login API response body.
C. An error because cy.wrap cannot be used inside then.
D. The entire response object instead of just the token.

Solution

  1. Step 1: Understand cy.request and then callback

    The then receives the response object from the POST request.
  2. Step 2: Extract token from response.body.token

    The code assigns token to the token string from the response body and saves it as an alias.
  3. Final Answer:

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

    Response body token is saved as alias [OK]
Hint: Response body holds token; alias saves it for later [OK]
Common Mistakes:
  • Thinking token is undefined outside callback
  • Believing cy.wrap cannot be used inside then
  • Confusing response object with token string
4. You wrote this code to login programmatically but your test fails because the session is not preserved:
cy.request('POST', '/login', { username: 'user', password: 'pass' })
cy.visit('/dashboard')

What is the most likely reason?
medium
A. You forgot to save and set the authentication cookie or token after login.
B. The cy.visit command must come before cy.request.
C. The login API endpoint does not support POST requests.
D. You need to add cy.wait() between the commands.

Solution

  1. Step 1: Understand session preservation in Cypress

    After login via cy.request, you must save cookies or tokens to keep the session.
  2. Step 2: Identify missing step in code

    The code does not save or set any authentication cookie or token before visiting the dashboard.
  3. Final Answer:

    You forgot to save and set the authentication cookie or token after login. -> Option A
  4. Quick Check:

    Session needs saved cookie/token after login [OK]
Hint: Save auth cookie/token after login to keep session [OK]
Common Mistakes:
  • Assuming cy.visit order matters here
  • Thinking login API rejects POST requests
  • Adding unnecessary waits instead of fixing session
5. 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
A. Cypress.Commands.add('login', () => { cy.request('GET', '/api/login') .then((res) => { cy.setCookie('authToken', res.body.token) }) })
B. Cypress.Commands.add('login', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() })
C. Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { username: 'user', password: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) })
D. Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { user: 'user', pass: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) })

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]
Hint: 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
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