【问题标题】:Cypress assertion fails but test passes赛普拉斯断言失败但测试通过
【发布时间】:2021-01-15 13:30:43
【问题描述】:

对 API 进行一些集成测试。 当断言基本相同时,一个测试通过,另一个失败。 对 cypress 如何处理异步/承诺感到困惑。

context("Login", () => {
  // This test fails
  it("Should return 401, missing credentials", () => {
    cy.request({
      url: "/auth/login",
      method: "POST",
      failOnStatusCode: false
    }).should(({ status, body }) => {
      expect(status).to.eq(401) // Passes
      expect(body).to.have.property("data") // Passes
                  .to.have.property("thisDoesntExist") // Fails
    })
  })
  
  // This test passes
  it("Should return 200 and user object", async () => {
    const token = await cy.task("generateJwt", users[0])
    cy.request({
      url: "/auth/me",
      method: "GET",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-type": "application/json"
      }
    }).should(({ status, body }) => {
      expect(status).to.eq(200) // Passes
      expect(body).to.have.property("data") // Passes
                  .to.have.property("thisDoesntExist") // Fails
    })
  })
})

编辑: 我通过这样做修复了它:

 it("Should return 200 and user object", () => {
    cy.task("generateJwt", users[0]).then((result) => {
      const token = result
      cy.request({
        url: "/auth/me",
        method: "GET",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-type": "application/json"
        }
      }).should(({ status, body }) => {
        expect(status).to.eq(200)
        expect(body)
          .to.have.property("data")
          .to.have.property("thisDoesntExist")
      })
    })
  })

为什么在使用 async/await 时会通过?

【问题讨论】:

  • 如果您单击请求,它应该将详细信息写入开发工具控制台,包括响应。响应是什么样的?

标签: javascript node.js integration-testing cypress


【解决方案1】:

我看到您设法修复了您的代码。关于 async/await - Cypress 不支持它。见https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Commands-Are-Asynchronous

通常,赛普拉斯将所有操作排队,然后执行它们。因此,如果您的代码有任何同步部分,它将无法工作。此外,它们不支持 async/await 功能,因此使用这些功能的测试可能很不稳定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 2020-05-30
    • 2021-01-02
    • 1970-01-01
    • 2021-12-22
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多