Home > Software engineering >  How to wait until get certain value in API json response using Cypress
How to wait until get certain value in API json response using Cypress

Time:11-08

I am working on Cypress API and trying to get response but the problem I am facing is that I need to wait for some time for the next request until I get the response from previous one. For example, until "activated: true" and "fileType not inprogress".

[
    {
        "filenameSource": "test",
        "fileExt": "mp4",
        "uniqueId": "18564Cm_BTo7Q0Sb0xCT",
        "fileName": "test.mp4",
        "title": "Test Video",
        "language": "##",
        "validFrom": "2022-10-01T00:00:00.000Z",
        "rating": 0,
        "aspect": "null",
        "duration": -1,
        "fps": 0,
        "activated": false,
        "fileSize": 0,
        "importTime": "2022-11-07T12:14:31.813Z",
        "fileType": "inprogress"
    }
]

Please need some help to tackle such scenario. Thanks in advance!

CodePudding user response:

I think Request Polling is what you are trying to do

function req(attempts = 0) {

  if (attempts === 100) {
    throw new Error('Too many attempts')
  }

  cy.request('GET', ...)
    .then(resp => resp.json())
    .then(json => {

      const data = resp.body
      
      if (data[0].activated) {
        return                             // break out of the recursive loop
      }
      
      cy.wait(200)
      req(  attempts)                      // else recurse
    })
}

cy.request('POST', ...)          // initiate product

req()                            // wait for activated 

cy.request('DELETE', ...)        // now delete product

CodePudding user response:

I have managed to resolve it with Cypress recurse function. Here is the link https://www.npmjs.com/package/cypress-recurse.

Thanks!

  • Related