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

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

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

docs on wait来看,所有这些似乎都基于一个模型,在该模型中,网络请求是根据某些用户操作触发的,或者可以以某种方式进行排序,这反过来又笼统地说明了 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上的文档,但正在空白处。

解决方法

我找到了一个插件(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,这在项目中使用过,因此某些类型可能会过时未来。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-