skip to Main Content

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

2

Answers


  1. 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;
      })
    }
    
    Login or Signup to reply.
  2. You can apply failOnStatusCode directly to the cy.visit() command.

    For example

    const url = 'https://cypress.io/not-a-valid-page'
    cy.intercept(url).as('url')
    cy.visit(url, {failOnStatusCode: false})
    
    cy.wait('@url')
      .its('response')
      .then(response => {
        expect(response.statusCode).not.to.eq(200)
      })
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search