为什么 cy.intercept/cy.wait 无法捕获我的 HTTP 请求?

问题描述 投票:0回答:1

我正在尝试编写 Cypress (v13.1.0) 单元测试并使用

cy.intercept
捕获 HTTP
GET
调用。这个
GET
调用在用户按下按钮后发生。根据阅读文档,我按以下顺序设置测试:
cy.intercept
-{userActionHere}-
cy.wait
。但是,
GET
调用永远不会被拦截。

示例:

describe("API Tests", () => {
  it("get copy-style", () => {
    cy.intercept("GET", "http://localhost:7771/api/agent/report/copy-style").as("getStyle");

    openReport(undefined, testReport_demo);
    cy.visit("/#/");

    cy.get("rec-list").find('[data-cy="acceptButton"]').click();

    cy.wait("@getStyle").then((interception) => {
      console.log("The @getStyle result: ", interception);
    });
  });
});

结果:

Timed out retrying after 5000ms: cy.wait() timed out waiting 5000ms for the 1st request to the route: getStyle. No request ever occurred.

我也尝试了以下方法,结果相同,没有拦截:

  • 捕获任何 HTTP 请求(例如,
    cy.intercept("**")
    ),但仍然没有被拦截。
    • 在这种情况下,捕获了一些对某些图像资产的
      GET
      调用,但这些与我想要的无关。我对
      /api/agent/**
      的呼叫都没有被捕获。
  • cy.intercept
    中使用各种路径变体(例如,“api/agent/report/copy-style”、“api/agent/**”、“**api**”等)。
  • 在单击按钮之前移动
    wait
  • 增加等待超时(例如,
    cy.wait("@getStyle", {timeout: 30000}
  • 在等待之前使用
    cy.pause()
    手动单击 UI 中的按钮。
  • cy.wait()
    期间手动单击按钮。

在所有情况下,我都可以看到通过 WireShark 和/或在浏览器的“网络”选项卡中进行的 HTTP 调用,并且返回了正确的响应数据,但 Cypress 没有看到它。看到很多帖子提到

cy.server
cy.route
但这些似乎已被弃用。还没有找到对我有帮助的帖子。

unit-testing xmlhttprequest cypress cypress-intercept
1个回答
0
投票

它认为您对通配符匹配的各种尝试都不正确

  • cy.intercept("**")
    ->
    cy.intercept("*")
    包罗万象

当使用

**
作为路径段时,请确保包含路径分隔符
/

  • **/api/agent/report/copy-style
    用于域通配符

  • **/api/agent/**/*
    /api/agent/**/*
    用于任何 api/代理调用

  • **/api/**/*
    /api/**/*
    对于任何 api

也可以尝试Regexp

cy.intercept(/\/copy-style/)
© www.soinside.com 2019 - 2024. All rights reserved.