我们如何在赛普拉斯中等待网络请求?

时间:2020-08-23 07:36:31

标签: user-interface automated-tests integration-testing cypress e2e-testing

我试图验证是否触发了一个网络请求(记录了一个指标),但是该指标与特定的用户操作无关(该指标在视频播放2秒钟后就会触发)。

docs on wait来看,所有这些似乎都基于一个模型,在该模型中,网络请求是根据某些用户操作触发的,或者可以以某种方式进行排序,这反过来又笼统地说明了< strong> order (从某种意义上说,它不依赖于其他操作)和网络请求的 timing (与发送给其他网络请求的其他网络请求相比不是随机排序的)相同的端点)。

因此对于下面的示例,此方法之所以有效,是因为(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);
    });
});

事实证明,这是片状的(有时会通过,但会更频繁地失败),这并不是因为Cypress本身,而是因为在应用程序中如何触发指标,有两个原因:

  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. 我也想到了一个艰难的等待,但是赛普拉斯指南 字面意思 waiting for an arbitrary amount of time is an anti-pattern

    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测试中,是否有更好的策略来验证指标?

我已经阅读了wait functionbest practices regarding unnecessary waiting上的文档,但正在空白处。

1 个答案:

答案 0 :(得分:0)

我找到了一个插件(https://github.com/NoriSte/cypress-wait-until),该插件完全可以满足我的需求-它使我们可以等待Cypress不支持的其他任何事物,例如上面的网络请求示例。因此,在设置了插件之后,该代码段现在如下所示:

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": true更改为polyfill fetch,这在项目中使用过,因此某些类型可能会过时未来。