Cypress assertion fails but test passes

Viewed 1624

Doing some integration tests on API. One of the tests passes and the other fails when assertions are basically the same. Confused about how cypress handles async/promises.

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
    })
  })
})

EDIT: I fixed it by doing this:

 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")
      })
    })
  })

Why does it pass when using async/await?

Tests

1 Answers
Related