javascriptcypressweb-api-testing

Cypress TypeError : Cannot read properties of undefined (reading 'then')


I have this function below :- checkStatusCode

I check if a response is OK then I try to return a value and based on that I try to visit the URL (ex:- if response status is 200)

  checkStatusCode(href) {
    cy.request({
      url: href,
      failOnStatusCode: false,
    }).then((response) => {
      expect(response.status).to.eq(200);
      return true;
    });
  }

This is how I call the function, but I am getting following Cypress error

Cannot read properties of undefined (reading 'then')

even if the assertion expect(response.status).to.eq(200) passes, what am I doing wrong here?

navigatetoHomepage(url) {
    this.checkStatusCode(url).then((isStatus200) => {
      if (isStatus200) {
        cy.visit(url);
      } else {
        cy.log("Fail");
      }
    });
  }

Solution

  • If you return the cy.request() from the function you can apply .then() after the call, but that still won't do what you want to do.

    The expect() in the function negates the failOnStatusCode: false setting, because if status is not 200 the test stops there.

    Instead you should return true or false depending on the status code, and your main test can use it appropriately.

    checkStatusCode(href) {
      return cy.request({
        url: href,
        failOnStatusCode: false,
      }).then((response) => {
        return response.status === 200;
      })
    }