赛普拉斯请求重试

时间:2019-01-07 17:31:49

标签: cypress

在赛普拉斯测试中,我需要通过调用外部API来验证操作。 API调用将始终返回结果(来自先前的运行),因此我不能简单地调用一次并验证结果。我需要重试几次,直到找到与当前运行相匹配的整体超时/失败为止。获得当前结果所需的时间差异很大;我真的不能在这个电话之前疯狂地漫长的等待。
请参阅以下摘要中的评论;一旦我在循环中尝试一个请求,它就永远不会被调用。使用cy.wait得到了相同的结果。我也不能将实际请求包装在另一个返回Cypress.Promise或类似函数的函数中,该函数只会将问题推高一个堆栈帧。

Cypress.Commands.add("verifyExternalAction", (someComparisonValue) => { 

    const options = {
      "url": some_url,
      "auth": { "bearer": some_apikey },
      "headers": { "Accept": "application/json" }
    };

    //// This works fine; we hit the assertion inside then.
    cy.request(options).then((resp) => {
      assert.isTrue(resp.something > someComparisonValue);
    });

    //// We never enter then.
    let retry = 0;
    let foundMatch = false;
    while ((retry < 1) && (!foundMatch)) {
      cy.wait(10000);
      retry++;
      cy.request(options).then((resp) => {
        if (resp.something > someComparisonValue) {
          foundMatch = true;
        }
      });
    }
    assert.isTrue(foundMatch);

});

1 个答案:

答案 0 :(得分:1)

  1. 您不能将同步(while循环; assert.isTrue在cy命令之外...)和异步工作(cy命令)混合使用。阅读introduction to cypress #Chains-of-Commands
  2. 您的第一个请求正在声明resp.something值,如果失败,则整个命令将失败,因此不再重试。
  3. 您正在执行异步工作,因此无法await cypress命令(无论如何都没有这样做),因此您需要递归,而不是迭代。换句话说,你不能使用 while循环。

喜欢的东西应该可以工作:

Cypress.Commands.add("verifyExternalAction", (someComparisonValue) => {

    const options = {
        "url": some_url,
        "auth": { "bearer": some_apikey },
        "headers": { "Accept": "application/json" }
    };

    let retries = -1;

    function makeRequest () {
        retries++;
        return cy.request(options)
            .then( resp => {
                try {
                    expect( resp.body ).to.be.gt( someComparisonValue );
                } catch ( err ) {

                    if ( retries > 5 ) throw new Error(`retried too many times (${--retries})`)
                    return makeRequest();
                }
                return resp;
            });
    }

    return makeRequest();
});

如果您不希望赛普拉斯在重试期间记录所有失败的期望,请不要使用抛出的expect / assert并进行定期比较(并且可能仅在结束时声明)。 .then回调链接到最后一个makeRequest()调用)。

相关问题