Cypress: Network automation to emulate offline mode only works with DevTools open

Created on 3 Nov 2020  路  3Comments  路  Source: cypress-io/cypress

You can find the tests for this in https://github.com/cypress-io/cypress-example-recipes/pull/581

Imagine I want to test how the web app handles offline mode. I can turn the offline mode using CDP and confirm the window.navigator.onLine changes correctly

const goOffline = () => {
  cy.log('**offline**')
  .then(() => {
    return Cypress.automation('remote:debugger:protocol',
      {
        command: 'Network.emulateNetworkConditions',
        params: {
          offline: true,
          latency: -1,
          downloadThroughput: -1,
          uploadThroughput: -1,
        },
      })
  })
}
cy.wrap(window).its('navigator.onLine').should('be.false')

This works.

online-offline

Now imagine we actually _make_ fetch requests from the app, and in offline mode they should fail. Check this out - it works. They do fail, but only _when DevTools is open_. Once we close the DevTools, the navigator.onLine still changes as expected, but the network calls start all working, as if ignoring the offline mode emulation.

In the video below I run the test several times with DevTools open - it is passing as expected. But when I close the DevTools, the test fails.

says-offline-but-request-happens

Browsers: Electron 85, Chrome 86, 88, Edge 86

needs investigating bug

Most helpful comment

done, recipe merged

All 3 comments

Some sources, like https://github.com/cypress-io/cypress/pull/6932 use the command Network.enable first. Does that make any difference in your results @bahmutov ?

      // This seems to be important
      Cypress.automation('remote:debugger:protocol', {
        command: 'Network.enable',
      })

      Cypress.automation('remote:debugger:protocol', {
        command: 'Network.emulateNetworkConditions',
        params: {
          'offline': true,
          'latency': 0,
          'downloadThroughput': 0,
          'uploadThroughput': 0,
          'connectionType': 'none',
        },
      })

OMG @EtienneBruines YES. Of course. I guess when Devtools is opened, the network events are delivered anyway. This solves the problem, bravo 馃憦

offline-workd

done, recipe merged

Was this page helpful?
0 / 5 - 0 ratings