1

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");
      }
    });
  }
4
  • 1
    checkStatusCode(href) does not return anything. Thus, when you do checkStatusCode(href).then(...) you are calling then on a value of undefined Commented Aug 5, 2024 at 8:33
  • 1
    checkStatusCode doesn't return anything, nor is async, therefore it only returns undefined, not a promise. Commented Aug 5, 2024 at 8:33
  • 1
    This question is similar to: How do I return the response from an asynchronous call?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Aug 5, 2024 at 8:33
  • 2
    fix could be as simple as return cy.request({ Commented Aug 5, 2024 at 8:47

2 Answers 2

3

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;
  })
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This works too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.