【问题标题】:Making a test fail if an HTTP request fails in Cypress如果赛普拉斯中的 HTTP 请求失败,则使测试失败
【发布时间】:2021-01-20 20:37:28
【问题描述】:

我正在使用 Cypress 测试一个应用程序,这些测试针对的是真实的 HTTP 服务器。我没有对 HTTP 请求进行存根。

如果任何 HTTP 请求失败,有没有办法让我的测试失败?

this other SO post 有一个看起来不错的解决方案,但我想知道是否有更合适的解决方案。就我而言,我并不总是将所有 HTTP 错误都转换为对console.error 的调用。

【问题讨论】:

  • 我知道您可能有充分的理由这样做,但您是否考虑过使用 mswjs.io 之类的东西而不是真正的端点?

标签: cypress


【解决方案1】:

您可以使用 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])

【讨论】:

  • 谢谢!这对我来说非常有效,我可以截取* 的网址并确保代码在 200 到 399 之间。谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
相关资源
最近更新 更多