【问题标题】:Capture all XHR Requests with Cypress.io使用 Cypress.io 捕获所有 XHR 请求
【发布时间】:2019-09-09 15:27:44
【问题描述】:

当我调用 URL 时,会发送未定义数量的请求。

现在我尝试找出其中一个请求是否包含某个有效负载。

cy.server();
cy.visit(url);

cy.route({
    method: 'POST',
    url: '**/t/e/**',
}).as('xhrRequest');

到目前为止,我在How to capture all API calls in cypress? 上找到了类似的方法。 这里的问题是假设有固定数量的 API 调用。

cy.wait(Array(60).fill('@xhrRequest'), { timeout: 30000 }).then((xhrs) => {
    xhrs.forEach((res) => {
        expect(res.status).not.to.be.null
    })
})

如果没有包含有效负载的单个请求,我如何知道所有请求都被拦截并且我的测试失败。

我已经在 puppeteer 中写过类似的东西

let hasSpecialRequest = false; 
page.on('request', request => {
if (isSpecialRequest(request)) {
    hasSpecialRequest = true; 
}
request.continue();
});

await page.setRequestInterception(true);

expect(hasSpecialRequest).to.equal(true);

系统检查每个请求是否是特殊请求之一,并相应地设置变量。我尝试用 Cypress 重新创建这样的东西。

【问题讨论】:

    标签: javascript cypress


    【解决方案1】:

    您可能会考虑执行 cy.exec 并以另一种语言运行脚本并从子进程返回状态。

    【讨论】:

      【解决方案2】:

      我可能误解了这个问题,但由于我是通过 Google 考察来到这里的,也许这可能会帮助遇到我的问题的人,也可能是你。

      起初我使用cy.wait(@alias),但无法检索所有响应(只显示一个响应,我不知道如何访问所有响应)。所以我最终立即将响应存储到另一个数组中以在测试中访问。

      let xhrRequests;
      
      function getXhrRequests() {
          xhrRequests = [];
      
          cy.intercept('GET', '**', (res) => {
              xhrRequests.push(res);
          });
      
          return xhrRequests;
      }
      
      describe('Some', function () {
          it('Thing 1', () => {
              let thing1 = getXhrRequests();
              cy.visit('http://some.site');
              thing1.forEach((res) => {
                  expect(res.status).not.to.be.null;
              })
          }
      
          it('Thing 2', () => {
              let thing2 = getXhrRequests();
              cy.visit('http://some.site/2');
              thing2.forEach((res) => {
                  expect(res.status).not.to.be.null;
              })
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2018-04-27
        • 2016-10-15
        • 2020-05-24
        • 1970-01-01
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        • 1970-01-01
        • 2018-08-31
        相关资源
        最近更新 更多