steal-socket.io
Wrap SocketIO client for SSR and testing.
The steal-socket.io
module exports a function that wraps socket.io
to serve the following purposes:
- Ignore
socket.io
for server-side rendering (SSR). - Ignore
socket.io
for can-zone. - Proxy and delay
socket.io
connection for testing.
stealSocket( url, [options] )
Since this is a wrapper around SocketIO io
function it supports all the same arguments as socket.io does.
var io = require("steal-socket.io");
var socket = io("localhost", {transports: ["websocket"]});
Parameters
-
url
{String}
A URL for
socket.io
connection. -
options
{Object}
OptionalOptional parameters to be passed to
socket.io
.
Returns
{ProxySocket}
A proxy socket that can delay establishing socket.io
connection.
Ignore SSR
If your application uses real-time communication with
socket.io
and your server supports SSR then its a good idea to ignoresocket.io
module during SSR completely.The
steal-socket.io
module mapssocket.io-client/dist/socket.io
to an@empty
module, and stubssocket.io
as minimally as possible.Ignore can-zone
This wrapper is aware of can-zone module which helps to track asynchronous activity. It uses
can-zone.ignore
to skip the tracking ofsocket.io
calls. For more information about whatcan-zone
is checkout this article as well as the documentation.Proxy and delay socket.io connection
This wrapper helps with testing and demoing applications that use
socket.io
for real-time communication.Often some modules that use socket.io call it to establish a socket connection immediately. This makes mocking of socket.io impossible.
The wrapper delays the creation of socket connection till StealJS is done with loading all the modules (including the ones where we can mock socket.io).
How it works
The
delay-io
wrapper returnsio
-like function that resolves with aProxySocket
. TheProxySocket
is a replacement forio.Socket
and acts as a proxy for it.Initially the wrapper records all calls to
io
and its socket into a FIFO storage, and then, whenStealJS
is done with loading all modules, it replays the recorded calls against the realio
and its socket.After replaying the wrapper directly proxies all the subsequent calls.
Usage
Import
steal-socket.io
which includes this wrapper as its part, or directly importsteal-socket.io/delay-io
to use just this wrapper.Lets say we have an application
myApp.js
that usessocket.io
and tries to establish the connection right during module evaluation. We importsteal-socket.io
in our app instead ofsocket.io-client/dist/socket.io
:We now create a module
myFixtureSocket.js
that mockssocket.io
server responses, e.g. using can-fixture-socket:And then we can test our application like this: