如何等待API json响应中的某个值

问题描述 投票:0回答:2

我正在研究 Cypress API,试图获得特定的响应,但问题是我需要等到获得特定的响应,与之前的响应不同。

例如,重复直到

"activated: true"
"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"
    }
]
cypress web-api-testing
2个回答
4
投票

我认为请求轮询就是您正在尝试做的事情

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

-1
投票

我已经设法用 Cypress 递归函数解决了这个问题。这是链接https://www.npmjs.com/package/cypress-recurse

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.