首页 > 解决方案 > 我们如何在 Cypress 中等待网络请求?

问题描述

我正在尝试验证已触发网络请求(记录指标),但该指标与特定用户操作无关(在视频播放 2 秒后触发指标)。

docs on 开始wait,所有这些似乎都基于一个模型,其中网络请求在某些用户操作上触发或可以以某种方式排序,这反过来又推广到顺序可预测的情况(从某种意义上说,它不依赖于另一个动作)和网络请求的时间(与其他向同一端点触发的网络请求相比,它不是随机排序的)。

因此,对于下面的示例,这是有效的,因为 (1) 具有可预测的顺序(它始终遵循点击操作),并且 (2) 时间遵循用户每次点击的时间(任何地方都不会有第二次请求到同一端点在点击和网络请求之间触发)。

beforeEach(() => {
  // omitting setup code
  cy.server();
  cy.route({ method: 'POST', url: VISUAL_MODE_ENDPOINT }).as('visual-mode-toggle');
});

it('should save the visual mode preference and change the page to dark mode', () => {
  cy.get('.visual-mode-toggle').click();
  cy.wait('@visual-mode-toggle')
    .get(xhr => {/* omitting asserting the request is fired and returns a 200 */});
  
  // UI tests omitted
});

但是,对于我的用例,我希望能够断言某些指标已被触发。我正在构建的应用程序通过网络调用记录了许多指标,但我只想测试一个特定的指标。(注意:所有指标都记录到同一个端点。)所以我尝试了这样的事情:

beforeEach(() => {
  cy.server();
  cy.route({ method: 'POST', url: METRICS_ENDPOINT }).as('metrics');
});

it('should fire a metric when the video is viewed for more than 2 seconds', () => {
  cy.wait('@metrics') // this is problematic
    .get<Cypress.WaitXHR[]>('@metrics.all')
    .then(xhrs => {
      const videoPlayInViewportRequests = Array
        .from(xhrs)
        .filter(isVideoPlayInViewport);

      videoPlayInViewportRequests.forEach(xhr => expect(getJSONPayload(xhr)).to.include('viewers'));
      
      expect(videoPlayInViewportRequests.length).to.not.equal(0);
    });
});

事实证明这是不稳定的(它有时会通过,但失败的频率更高),不是因为赛普拉斯本身,而是因为应用程序中的指标是如何触发的,原因有两个:

  1. 不可预知的顺序。除了这个“播放至少 2 秒”指标之外,还有其他指标在两者之间发出,例如播放器加载第一帧所需的时间,以及其他页面加载指标。没有逻辑可以保证这些指标的顺序,这使得无法确定它们被触发的顺序。

  2. 不可预知的时机。我们也不知道它何时出现。有时,该指标恰好在重试限制内被触发,但有时,它不会。

因此我们得到以下场景(假设重试限制为 5 秒,并且所有指标都通过同一个端点触发):

  1. 2 秒指标(3 秒)-> 其他指标(7 秒)(成功,因为这是我们等待的第一个网络请求cy.wait
  2. 2 秒指标(6 秒)-> 其他指标(7 秒)(失败,因为在重试限制后触发)
  3. 其他指标(2 秒)-> 2 秒指标(3 秒)(失败,因为我们只调用了cy.wait一次)
  4. 其他指标(6 秒)-> 2 秒指标(7 秒)(失败,超出重试限制)

如果我们编写cy.wait('@metrics').wait('@metrics'),它可以修复场景 3,但不能保证,因为在这两者之间可能会触发更多的指标。

所以我的问题是:

  1. 在这种情况下我们如何实现等待?我在想像循环一样的东西,直到我们找到我们正在寻找的东西,但它似乎非常不像赛普拉斯:

    let needToWait = true;
    const startTime = Date.now();
    
    do {
      cy.wait('@metrics')
        .get<Cypress.WaitXHR[]>('@metrics.all')
        .then(xhrs => {
          const results = Array.from(xhrs).filter(isVideoPlayInViewport);
          const hasVideoPlayInViewport = results.length !== 0;
          const timeExceededLimit = (Date.now() - startTime) > 10000;
          needToWait = !hasVideoPlayInViewport && !timeExceededLimit;
        }); 
    } while (needToWait);
    
  2. 我也考虑过等待,但赛普拉斯指南字面上等待任意时间是一种反模式

    cy.wait(7000); // this is pretty much the same thing as the above I guess lol, but the above can short circuit the loop once it's found, this doesn't
    
    // verify metric is present
    
  3. 测试指标是否属于赛普拉斯的用例?作为 UI 测试的一部分,是否有更好的策略来验证指标?

我已经阅读了有关等待功能的文档以及有关不必要等待的最佳实践,但我还是一片空白。

标签: user-interfaceautomated-testsintegration-testingcypresse2e-testing

解决方案


我找到了一个插件(https://github.com/NoriSte/cypress-wait-until),它完全符合我的要求 - 它允许我们等待赛普拉斯不支持等待的任何其他内容,比如网络请求上面的例子。所以在设置插件之后,代码片段现在看起来像这样:

cy.waitUntil(() => cy
      // stubbed according to https://docs.cypress.io/guides/guides/network-requests.html#Stubbing
      .get<Cypress.WaitXHR[]>('@metrics.all')
      .then(xhrs => {
        const videoPlayInViewportRequests = Array
          .from(xhrs)
          .filter(isVideoPlayInViewport);

        // 0 is falsy and will trigger retry, else return XHR requests to be yielded
        return videoPlayInViewportRequests.length && videoPlayInViewportRequests;
      }))
      // also not sure why but this param type is incorrectly inferenced as `undefined`
      .then(videoPlayInViewportRequests => videoPlayInViewportRequests
        .forEach((xhr: Cypress.WaitXHR) => expect(getJSONPayload(xhr)).to.include('viewers')));

未来说明我不得不将项目中使用的"experimentalFetchPolyfill": truepolyfill转换fetch为,因此某些类型将来可能会过时。


推荐阅读