 
                        我决定使用 Vite、Chakra-UI 和 TypeScript 构建一个 React 应用程序,并在 Cypress 中完成测试。目标是更多地了解其中一些技术。巧合的是,这是我第一次使用 Cypress。
不幸的是,我在 E2E 测试中遇到了有关测试 .wait() 的问题。该错误具体如下:CypressError:5000ms后超时重试:cy.wait()超时等待5000ms对于路由的第一个请求:getGames。从未发生任何请求。 我见过很多关于在访问页面之前首先进行存根然后等待调用的建议。然而,经过多次尝试,我似乎无法让等待呼叫不超时。我最近的尝试是在 beforeEach-ing 访问函数调用之前的 before 调用中进行拦截。正如您从我上传的图像中看到的,截距似乎已注册,但从未增加。
有没有人遇到过这种情况,并且有可能的解决方案?预先感谢您!
赛普拉斯控制台:
我有一个定义为 games.json 的固定装置,其中包含以下内容:
[
  {
    "id": 1,
    "name": "The Witcher 3: Wild Hunt",
    "background_image": "https://media.rawg.io/media/crop/600/400/games/618/618c2031a07bbff6b4f611f10b6bcdbc.jpg",
    "parent_platforms": [
      { "id": 1, "name": "PC", "slug": "pc" },
      { "id": 2, "name": "PlayStation", "slug": "playstation" },
      { "id": 3, "name": "Xbox", "slug": "xbox" },
      { "id": 7, "name": "Nintendo", "slug": "nintendo" }
    ],
    "metacritic": "92"
  },
  {
    "id": 2,
    "name": "BioShock Infinite",
    "background_image": "https://media.rawg.io/media/crop/600/400/games/fc1/fc1307a2774506b5bd65d7e8424664a7.jpg",
    "parent_platforms": [
      { "id": 1, "name": "PC", "slug": "pc" },
      { "id": 2, "name": "PlayStation", "slug": "playstation" },
      { "id": 3, "name": "Xbox", "slug": "xbox" },
      { "id": 6, "name": "Linux", "slug": "linux" },
      { "id": 7, "name": "Nintendo", "slug": "nintendo" }
    ],
    "metacritic": "94"
  }
]
../support/commands.ts:
const baseURL = "**http://api.rawg.io/api*";
Cypress.Commands.add("landing", () => {
  cy.intercept("GET", `${baseURL}/games`, { fixture: "games.json" }).as(
    "getGames"
  );
});
还有我的测试文件:
describe("The Home Page", () => {
  before(() => {
    cy.landing();
  });
  beforeEach(() => {
    cy.visit("/");
  });
  it("successfully loads", () => {
    cy.wait("@getGames");
  });
});            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
首先,您应该使用正确的协议 -
https://api.rawg.io/api。其次,
https://api.rawg.io/api之前没有任何内容,因此前面加通配符**是不正确的。第三,在路径分隔符
/或//之前或之后放置通配符。最后,不要在
before()中放置拦截,因为它会在测试之间被清除。放入beforeEach()describe("The Home Page", () => { beforeEach(() => { // these all work (use only one) cy.intercept('https://api.rawg.io/api/games?key=my-key-goes-here').as('games') cy.intercept('**/api/games?key=my-key-goes-here').as('games') cy.intercept('**/api/games?*').as('games') cy.intercept('**/api/*').as('games') cy.intercept('**//api.rawg.io/api/*').as('games') cy.intercept({pathname: '**/api/*'}).as('games') cy.intercept({pathname: '**/api/games'}).as('games') cy.visit("/"); }); it("successfully loads", () => { cy.wait("@games") .its('response.body.count') .should('be.gt', 900000) }) it("successfully loads again", () => { cy.wait("@games") .its('response.body.count') .should('be.gt', 900000) }); })