【问题标题】:How to repeat a request until getting a different response in Cypress如何重复请求直到在赛普拉斯得到不同的响应
【发布时间】:2021-09-06 15:44:09
【问题描述】:

我正在处理链式请求,需要等到满足某个条件才能测试响应。先前的请求将始终返回响应,但我需要它的状态为“完成”,有时它是“进行中”。我不想对此 cy.wait() 使用静态等待,因为这会使测试变得不稳定或永远持续下去。我能怎么做? 到目前为止,这是我的代码,但它被卡住并且永远不会完成。使用静态等待(无循环)效果很好。

有什么想法吗?

it('name of the test', function() {
  cy.processFile().then((response) => {
    let i=0;
    while (i<5){
     cy.wait(1000);
     cy.getInfo().then((resp) => {
     if(resp.body.status !== 'finished'){
       i++;
     } else {
         i = 5;
         expect(.....);
       }
     })
   }
  })
})

【问题讨论】:

    标签: javascript mocha.js cypress


    【解决方案1】:

    while (i&lt;5) { 语句是同步的,它会在测试开始之前运行五次迭代。

    相反,这应该可以工作

    function waitForStatus (status, count = 0) {
    
      if (count === 5) {
        throw 'Never finished'
      }
    
      return cy.getInfo().then(resp => {
        if (resp.body.status !== status) {
          cy.wait(1000)                       // may not need to wait
          waitForStatus(status, ++count)      // run again, up to 5 times
        } else {
          return resp  // in case you want to expect(resp)...
        }
      })
    }
    
    cy.processFile().then((response) => {
      waitForStatus('finished').then(resp => {
        expect(resp)...
      })
    })
    

    这里有更详细的信息Writing a Cypress Recursive Function

    你的场景

    npm i -D cypress-recurse
    # or use Yarn
    yarn add -D cypress-recurse
    
    import { recurse } from 'cypress-recurse'
    
    it('waits for status', () => {
    
      cy.processFile().then((response) => {
    
        recurse(
          () => cy.getInfo(),
          (resp) => resp.body.status === 'finished',
          {
            log: true,
            limit: 5, // max number of iterations
            timeout: 30000, // time limit in ms
            delay: 1000 // delay before next iteration, ms
          },
        )
        .then(resp => {
          expect(resp)...
        })
    })
    
    

    【讨论】:

    • 这是一个很好的解决方法。我正在尝试您发送的第一个块(“这应该可以工作”下的那个),但我在 getInfo(resp.id) 中发送了一个参数,有时会被读取,有时不会。不知道为什么 ``` it('测试名称', function() { cy.processFile().then((response) => { let i=0; while (i { if(resp.body.status !== 'finished'){ i++; } else { i = 5; expect(..... ); } }) } }) }) ```
    猜你喜欢
    • 2019-09-23
    • 2021-08-08
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2020-05-09
    相关资源
    最近更新 更多