首页 > 解决方案 > 如何使 Cypress 中的请求调用更稳定

问题描述

当我在赛普拉斯测试中观看某些路线时,它失败了 1/8 次。有没有办法让赛普拉斯测试总是通过,而不是在多次尝试后随机失败?

这是我的代码:

it("Check if scroll is working on list", () => {
  cy.server()
  cy.route('GET', '**/api/scorer/company/news/**', { timeout: 15000 }).as('loadMoreAbstracts'); 
  cy.get('[data-cy=VirtualScroll]', { timeout: 15000 }).eq(1).scrollTo("bottom").then(()=>{
    cy.wait('@loadMoreAbstracts', { timeout: 15000 }).its('status').should('equal', 200);
  })
  cy.get('[data-cy=VirtualScroll]', { timeout: 15000 }).eq(1).invoke('scrollTop').should('be.gt', 0)
  
  cy.get('[data-cy=VirtualScroll]', { timeout: 15000 }).eq(1).scrollTo("bottom")
})

我看不出这段代码有什么问题,但不知何故,它时不时地无缘无故地失败。有一些东西使它不稳定,但是有没有办法让赛普拉斯测试更稳定?

我得到的错误是:

CypressError: Timed out retrying: `cy.wait()` timed out waiting `15000ms` for the 1st request to the route: `loadMoreAbstracts`. No request ever occurred.

标签: vue.jscypresse2e-testing

解决方案


我不确定,但看起来您正在使用外部 API 来获取数据。这自然会在您的测试中引入可变时间,从而导致一些失败。

如果您使用cy.intercept()(cy.route()已弃用),那么您可以提供一个响应对象来满足请求。这样做的好处是它将消除外部(和高度可变的)依赖,并且应该使您的测试更加可靠。

副作用也将是测试将运行得更快。


推荐阅读