我正在使用 Cypress 测试一个应用程序,这些测试针对真实的 HTTP 服务器。我不会存根 HTTP 请求。
如果任何 HTTP 请求失败,有没有办法让我的测试失败?
this other SO post 中有一个看起来不错的解决方案,但我想知道是否有更合适的解决方案。就我而言,我并不总是将所有 HTTP 错误转换为对 console.error
的调用。
答案 0 :(得分:2)
您可以使用 cy.intercept() 监听请求并检查状态代码等
参考:https://docs.cypress.io/api/commands/intercept.html#Intercepting-a-response
示例 1:
// Wait for intercepted HTTP request
cy.intercept('POST', '/users').as('createUser')
// ...
cy.wait('@createUser')
.then(({ request, response }) => {
expect(response.statusCode).to.eq(200)
})
示例 2:
// Listen to GET to comments/1
cy.intercept('GET', '**/comments/*').as('getComment')
// we have code that gets a comment when
// the button is clicked in scripts.js
cy.get('.network-btn').click()
// https://on.cypress.io/wait
cy.wait('@getComment').its('response.statusCode').should('be.oneOf', [200, 304])