How to check a link to a server that does not respond

110 Views Asked by At

Using cy.request() with the link URL "http://www.alitots.co.uk/" fails with this error:

The request failed without a response

We attempted to make an http request to this URL but the request failed without a response.

We received this error at the network level:
Error: getaddrinfo ENOTFOUND www.alitots.co.uk

The request we sent was:
Method: GET
URL: http://www.alitots.co.uk/

How do I handle this and carry on checking the other links?

This is the full code:

  cy.get("a:not([href*='mailto:'])").each(($link, index) => {
    const href=$link.prop('href')
    cy.log(href)
    if (href) {
      cy.request({
        url: href, 
        failOnStatusCode:false,
        followRedirect:false,
        failOnNetworkError:false
      })
      .then((response)=>{
        if(response.status >= 400 || response.status == '(failed)') {
          cy.log(` *** link ${index +1} is Broken Link ***`)
          //brokenLinks++
         } else {
          cy.log(` *** link ${index+1} is Active Link ***`) 
         }
       })
     }
  })
1

There are 1 best solutions below

3
Lola Ichingbola On

The error code ENOTFOUND means the server is not running.

All you are testing at the moment is the response, but there is no server to give a response.

You need to add a ping. If you do it manually in the terminal ping http://www.alitots.co.uk:

Ping request could not find host http://www.alitots.co.uk. Please check the name and try again.


This question gives you a way to ping the server from within the test

Checking if host is online in Cypress

result.stdout contains the same message as above.

  cy.get("a:not([href*='mailto:'])").each(($link, index) => {
    const href = $link.prop('href')
    if (!href) return

    const url = new URL(href)
    const host = url.hostname
    cy.exec(`ping ${host}`, {failOnNonZeroExit:false}).then(reply => {

      if (result.code !== 0) {
        cy.log(`Could not ping "${href}", result.stdout`)
      } else {

        // now check response
        cy.request({url: href, failOnStatusCode:false, followRedirect:false})
          .then(response => {
            if(response.status >= 400 || response.status == '(failed)') {
              cy.log(` *** link ${index +1} is Broken Link ***`)
              //brokenLinks++
            } else {
              cy.log(` *** link ${index+1} is Active Link ***`) 
            }
          })
      }
    })
  })