OSW
OSW

Reputation: 107

Cypress - get DOM element after calling bunch of requests

I am trying to write a test that can wait the bunch of requests as below complete, and then I can see the account info. I have tried the cy.wait, however, it not works ideally as I expected because sometimes the request back slowly, so Cypress can not detect the DOM element and report errors.

At Network tab on Chrome

postUrl - post request
postUrl - post request
postUrl - post request
postUrl - post request
getUrl - get request
getUrl - get request
getUrl - get request

So, I used for loop and cy.intercept, like following code. But, it would cause infinite loop that calling the first postUrl continually

const bunch = []
const accountName = [xx, yy, zz, aa]
for(let i = 0; i< accountName.length; i++) {
  cy.intercept({
     url
     method

  }).as(`req${accountName[i]}`)
  bunch.push(`req${accountName[i]}`)
}

cy.wait(bunch)

Only thing that I would like is that precisely wait the bunch of requests complete, like wait for all request finishs, then I can do following test.

Upvotes: 0

Views: 338

Answers (1)

Eddy Gilmour
Eddy Gilmour

Reputation: 3210

Th difference between the alias name in cy.intercept(...).as('reqXX') and cy.wait('@reqXX') is @, which is missing in your code.

The loop itself should be ok.

const bunchOfAliases = []
const accountName = [xx, yy, zz, aa]
for(let i = 0; i< accountName.length; i++) {
  const alias = `req${accountName[i]}`
  cy.intercept({
     url
     method
  }).as(alias)
  bunchOfAliases.push(alias)
}

const waitAliases = bunchOfAliases.map(alias => `@{alias}`)  // add @

cy.wait(...waitAliases)  // destructure the array

or simpler

const accountNames = [xx, yy, zz, aa]
accountNames.forEach(accountName => {
  cy.intercept({
     url
     method
  }).as(`req${accountName}`)
}

const waitAliases = accountNames.map(accountName => `@req${accountName}`)  // add @

cy.wait(...waitAliases)  // destructure the array

Upvotes: 1

Related Questions