API request calls not waiting in Cypress test

Viewed 30

I have a request that triggers another request that has a value needed later in the test.

I queued the code that uses the value, but still it is undefined. What an I doing wrong?

let val;
cy.request(api).then(response => {
  return fetch(`url-${response.id}`).then(response2 => {
    val = response2.id
  })
})

cy.then(() => {
  console.log('val', val)  // undefined
})
1 Answers

Add a Promise around the inner request, and return it.

Cypress automatically waits for promises to resolve.


let val;
cy.request(api).then(response => {
  return new Cypress.Promise(resolve => {
    fetch(`url-${response.id}`).then(response2 => {
      val = response2.id
      resolve()              // signals to Cypress that 2nd request has completed
    })
})

cy.then(() => {
  console.log('val', val)  // passes
})

Related