But the test fails with "Cannot read property 'then' of undefined". What is the likely cause?
medium
A. The cy.get('@itemId') runs before the alias is set.
B. The API returned status 500 causing failure.
C. The cy.request method is misspelled.
D. The cy.wrap command cannot create aliases.
Solution
Step 1: Understand Cypress command chaining and timing
Cypress commands run asynchronously and in order, but alias usage requires the alias to be set before use.
Step 2: Identify timing issue with alias usage
cy.get('@itemId') is called immediately, before the alias is set inside the then callback, causing undefined error.
Final Answer:
The cy.get('@itemId') runs before the alias is set. -> Option A
Quick Check:
Alias must be set before cy.get() uses it [OK]
Hint: Set alias before using cy.get('@alias') to avoid timing errors [OK]
Common Mistakes:
Assuming API error causes this specific error
Thinking cy.request is misspelled
Believing cy.wrap cannot create aliases
5. 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?
hard
A. users.forEach(user => {
cy.request('POST', '/api/users', user)
cy.visit('/users')
})
C. for (const user of users) {
cy.request('POST', '/api/users', user)
cy.visit('/users')
}
D. cy.wrap(users).each(user => {
cy.request('POST', '/api/users', user)
})
cy.visit('/users')
Solution
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.
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.