Bird
0
0

You want to use API-first setup to create multiple users before a UI test. Which approach correctly ensures all users are created before visiting the page?

hard📝 Application Q15 of 15
Cypress - Test Organization and Patterns
You want to use API-first setup to create multiple users before a UI test. Which approach correctly ensures all users are created before visiting the page?
const users = [
  {name: 'Anna'},
  {name: 'Ben'},
  {name: 'Cara'}
]

// Which code snippet is correct?
Ausers.forEach(user => { cy.request('POST', '/api/users', user) cy.visit('/users') })
Bcy.wrap(users).each(user => { cy.request('POST', '/api/users', user) }).then(() => { cy.visit('/users') })
Cfor (const user of users) { cy.request('POST', '/api/users', user) cy.visit('/users') }
Dcy.wrap(users).each(user => { cy.request('POST', '/api/users', user) }) cy.visit('/users')
Step-by-Step Solution
Solution:
  1. Step 1: Understand Cypress command queue and async behavior

    Cypress commands like cy.request are asynchronous and queued. To wait for all requests, use cy.wrap().each() with a .then() callback.
  2. Step 2: Analyze each option

    The native forEach and for-of options place cy.visit() inside the loop, causing visits after each request instead of after all. The cy.wrap(users).each(...) cy.visit() executes visit before requests due to queuing. Only cy.wrap(users).each(...).then(() => cy.visit()) waits for all requests before visiting.
  3. Final Answer:

    cy.wrap(users).each(user => { cy.request('POST', '/api/users', user) }).then(() => { cy.visit('/users') }) -> Option B
  4. Quick Check:

    Use cy.wrap().each() with then() to wait before next step [OK]
Quick Trick: Chain .then() after cy.wrap().each() to wait for all API calls [OK]
Common Mistakes:
  • Placing cy.visit() inside the forEach or for-of loop
  • Using cy.wrap().each() without .then() afterward
  • Not chaining .then() to wait for all iterations

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes