5

My problem

I am looking to test how a script handles a loss of internet connection part way through execution. At a lower level I simply need to cause a number of network request to fail after certain point in the script.

I am attempting to keep this test as end to end as possible without mocking any javascript units.

My thoughts on how I might achieve this

Chrome has a useful toggle in it's dev tools under the network tab which simulates a loss of internet connection. I would like to toggle this from the script I am executing (in a similar manner to how debugger triggers a breakpoint under the sources tab).

I suspect this won't be easy as it would create a significant security hole if web pages could trigger this. However, if there is anyway to hack Chrome into a state where it is possible, possibly using an extension or Chromium I'm all ears.

Is there a way to toggle the Chrome 'offline' dev tool from javascript?

Failing this is there any other way to simulate a loss of connection / cause network requests to fail from javascript? (By the way I'm not married to Chrome)

Community
  • 1
  • 1
thodic
  • 2,229
  • 1
  • 19
  • 35

4 Answers4

3

You could create a custom chrome extension with the debugger permission and then attach to the tab. Then you would call Network.enable on that tab and then start emulating network conditions (e.g. go offline)

You could communicate with your custom extension (e.g. telling it to go offline at a specific time) using onMessageExternal.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
kzahel
  • 2,765
  • 1
  • 22
  • 31
1

Maybe also try this?

setInterval("stop()", 100);

According to docs, window.stop() stops the currently-loading resources from loading, like pressing the "stop" button. Repeatedly doing that on a loop would simulate a network loss.

If you wanted to programmatically disconnect and also restore the connection, maybe something like

var interval = setInterval("stop()", 100);
// To restore connectivity
clearInterval(interval);
Frank
  • 81
  • 1
  • 2
  • 11
0

An easier way would be to set a breakpoint in the Sources tab at the critical point & then manually go offline in the Network tab.

0

Since you are on Javascript try leveraging asynchronous calls or promises to simulate this scenario.

Julia Meshcheryakova
  • 3,162
  • 3
  • 22
  • 42
Damascus
  • 19
  • 6