createChaosWebSocket
Create a WebSocket class that injects network faults, to pass as the WebSocket option during development.
Available only from react-websocket/chaos. It has no React dependency and doesn't import the client.
Usage
The guide is Chaos testing.
Parameters
Durations are in ms. A [min, max] range picks a uniformly random value each time it's used. Probabilities are from 0 to 1.
Returns
ChaosWebSocket: a class you can pass anywhere a typeof WebSocket is expected, with these static methods. Each acts on every connection the class made and is still open or connecting:
The methods work whether the random faults are enabled or not. Each call to createChaosWebSocket returns a new class with its own faults and connections.
Behavior
- Faults
latencydelays each event in order, each in its own task.refusefireserror, thenclosewith code1006, without creating the real socket. It never fires synchronously from the constructor.dropfireserror, thenclosewith code1006. It closes the real socket with4999 'chaos'.stallkeepsreadyStateatOPENand discards everything in both directions. The real socket'scloseevent is swallowed. Closing a stalled socket closes the real one with your code at once, and firesclosewith code1006a task later.corruptcuts text at a random point and appends U+FFFD, so it never parses as JSON. It cuts anArrayBufferorBlobshort. Any other data becomes'�'.dropandstalltogether: the first to come wins. A stalled connection can still drop later.
- Seeds. Each connection gets its own random sequences, one for its lifecycle (refusal, open delay, lifetimes), one for incoming and one for outgoing messages. With the same
seedand options, the nth connection gets the same faults no matter how much traffic earlier ones carried. - No faults, no delay. With no faults set, or
enabled: false, events pass through synchronously. - Like a browser
send()throwsInvalidStateErrorwhile connecting, and does nothing afterclose().close()throwsInvalidAccessErrorfor codes other than1000and3000–4999.bufferedAmountincludes sends held back bylatencyand anything sent into a stall.
- Not on the server. Without the
WebSocketoption and outside a browser, constructing it throws, so a client using it fails as during any server render. - Not a
WebSocket.instanceof WebSocketisfalse. Events have the chaos socket as theirtarget.