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.iofor server-side rendering (SSR). - Ignore
socket.iofor can-zone. - Proxy and delay
socket.ioconnection 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.ioconnection. -
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.ioand your server supports SSR then its a good idea to ignoresocket.iomodule during SSR completely.The
steal-socket.iomodule mapssocket.io-client/dist/socket.ioto an@emptymodule, and stubssocket.ioas minimally as possible.Ignore can-zone
This wrapper is aware of can-zone module which helps to track asynchronous activity. It uses
can-zone.ignoreto skip the tracking ofsocket.iocalls. For more information about whatcan-zoneis 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.iofor 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-iowrapper returnsio-like function that resolves with aProxySocket. TheProxySocketis a replacement forio.Socketand acts as a proxy for it.Initially the wrapper records all calls to
ioand its socket into a FIFO storage, and then, whenStealJSis done with loading all modules, it replays the recorded calls against the realioand its socket.After replaying the wrapper directly proxies all the subsequent calls.
Usage
Import
steal-socket.iowhich includes this wrapper as its part, or directly importsteal-socket.io/delay-ioto use just this wrapper.Lets say we have an application
myApp.jsthat usessocket.ioand tries to establish the connection right during module evaluation. We importsteal-socket.ioin our app instead ofsocket.io-client/dist/socket.io:We now create a module
myFixtureSocket.jsthat mockssocket.ioserver responses, e.g. using can-fixture-socket:And then we can test our application like this: