2
votes

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
If you click on the request, it should write the details to the Dev Tools console, including the response. What does the response look like? - MetaWhirledPeas

1 Answers

0
votes

I see that you manage to fix your code. About the async/await - Cypress does not support it. See https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Commands-Are-Asynchronous.

In general, Cypress queue all the actions and then execute them. So if your code has any synchronous part it will not work. Also, they're not supporting the async/await feature, so tests using those might be flaky.