cypresspingweb-testing

Checking if host is online in Cypress


My tests run on a IOT device which is controlled via a web interface. I want to create a factory reset test which involves a reboot of the device and I want to check in a loop if the device is online ("pingable") again. Is there a way to execute the ping command inside of Cypress and get a return value of it.


Solution

  • Presuming you mean the standard ping protocol, this is the form. Substitute your device address and reply message.

    cy.exec('ping google.com', {failOnNonZeroExit: false})
      .then(reply => {
        expect(reply.code).to.eq(0)
        const expectedMsg = 'Pinging google.com [142.250.66.206] with 32 bytes of data:\r\nReply from 142.250.66.206: bytes=32' 
        expect(reply.stdout).to.satisfy(msg => msg.startsWith(expectedMsg))
      })
    

    A loop may not be needed, but if so I'd use a recursive function

    function doPing(count = 0) {
    
      if (count === 10) throw 'Failed to ping';
    
      cy.exec('ping google.com', {failOnNonZeroExit: false})
        .then(reply => {
          if (reply.code > 0) {
    
            cy.wait(1000)    // whatever back-off time is required
            doPing(++count)
    
          } else {
            expect(reply.stdout).to.satisfy(msg => ...)
          }
        })
    }
    
    doPing()