在赛普拉斯测试中加载页面后,如何可靠地等待XHR请求?

sch*_*pet 6 cypress

在我的应用程序中,当我访问页面时,它会发出一些网络请求以获取数据并将其显示在页面上。之后,您单击按钮并填写字段以过滤该数据。

我有一个赛普拉斯测试,基本上可以访问该页面,应用一些过滤器,并确保dom中的内容看起来正确:

it(`filters the data by 'price'`, () => {
  cy.server()
  cy.route('POST', 'http://my-api.biz/api').as('apiRequest')

  cy.visit('/')

  // initial page load loads the min and max price bounds for the UI,
  // as well as the data to initially populate the page. they happen
  // to hit the same URL with different POST params
  cy.wait(['@apiRequest', '@apiRequest'])

  cy.get('#price-filter-min').type('1000')
  cy.get('#price-filter-max').type('1400')

  // wait for data to get refreshed
  cy.wait('@apiRequest')

  cy
    .get('[data-test-column="price"]')
    .each($el => {
      const value = parseFloat($el.text())
      expect(value).to.be.gte(1000)
      expect(value).to.be.lte(1400)
    })
})
Run Code Online (Sandbox Code Playgroud)

但是有时柏似乎加载了页面,等待之前执行XHR请求,然后偶尔会失败:

CypressError:超时重试:cy.wait()超时,等待30000毫秒,对路由“ apiRequest”的第二次响应。从未发生任何回应。

因为它正在等待已经发生的请求。

有没有更好的方法编写此测试?有没有一种方法可以访问页面并等待XHR请求,从而避免出现这种竞争情况?

更新

我试图在一个隔离的测试用例中重新创建它,但似乎一切正常,因此可能存在一些操作员错误。

Alt*_*tus 9

所以现在大部分答案都被弃用了。从 Cypress@6.4.0 开始,您应该使用intercept().

这是我的做法:

cy.intercept({
      method: "GET",
      url: "http://my-api.biz/api/**",
    }).as("dataGetFirst");
cy.wait("@dataGetFirst");
Run Code Online (Sandbox Code Playgroud)

就是这样。你可以做更多的事情并在等待时做一个断言链,但它本身已经是一个断言。


Lui*_*uin 7

你可以做这样的事情

// Give an alias to request
cy.server().route("GET", /odata/locations/**).as('dataGetFirst')

// Visit site
cy.visit('admin/locations')

// Wait for response.status to be 200
cy.wait('@dataGetFirst').its('status').should('be', 200) 

// Continue
Run Code Online (Sandbox Code Playgroud)