reactjs CypressError:5000ms后超时`cy.wait()` ...未发生请求

y53ybaqx  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(196)

我决定使用Vite,Chakra-UI和TypeScript构建一个React应用程序,并在Cypress中进行测试。目标是更多地了解其中的一些技术。巧合的是,这是我第一次使用Cypress。
不幸的是,我在E2 E测试中遇到了关于测试.wait()的问题。该错误具体如下:CypressError: Timed out retrying after 5000ms:周期等待()timed out waiting 5000 ms for the 1st request to the route: getGames . No request ever occurred.我看到过很多关于先存根后访问页面再等待调用的建议。然而,经过多次尝试,我似乎不能让wait调用不超时。我最近的尝试是在beforeEach-ing访问函数调用之前拦截before调用。从我上传的图片中可以看到,拦截似乎已经注册,但从未增加。
有没有人遇到过这种情况,并有一个潜在的解决方案?提前感谢!
Cypress控制台:

我有一个定义为games.json的fixture,它包含以下内容:

[
  {
    "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");
  });
});
kcrjzv8t

kcrjzv8t1#

首先,您应该使用正确的协议-https://api.rawg.io/api
其次,https://api.rawg.io/api之前没有任何内容,因此使用通配符**是不正确的。
第三,在路径分隔符///之前或之后放置通配符。
最后,不要将截取放在before()中,因为它在测试之间会被清除。

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)
  });
})

相关问题