Bird
0
0

You wrote this API-first setup code in Cypress:

medium📝 Debug Q14 of 15
Cypress - Test Organization and Patterns
You wrote this API-first setup code in Cypress:
cy.request('POST', '/api/items', {name: 'Book'})
  .then((res) => {
    expect(res.status).to.eq(200)
    cy.wrap(res.body.id).as('itemId')
  })
cy.get('@itemId').then((id) => {
  cy.visit(`/items/${id}`)
})

But the test fails with "Cannot read property 'then' of undefined". What is the likely cause?
AThe <code>cy.get('@itemId')</code> runs before the alias is set.
BThe API returned status 500 causing failure.
CThe <code>cy.request</code> method is misspelled.
DThe <code>cy.wrap</code> command cannot create aliases.
Step-by-Step Solution
Solution:
  1. 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.
  2. 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.
  3. Final Answer:

    The cy.get('@itemId') runs before the alias is set. -> Option A
  4. Quick Check:

    Alias must be set before cy.get() uses it [OK]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes