How to stub a web socket (supplying only an event emitter like object) in javascript

784 Views Asked by At

I'm looking for the simplest way to stub in a custom event emitter when a socket connection is made. I realize this can be done w/ sinon (as shown below)

var socket = new io.EventEmitter();
sinon.stub(io, 'connect').returns(socket);
// initialization that causes io.connect to be invoked
socket.emit('connect');

Ideally I'm looking for what I see as a true "black box" stub that knows nothing of the underlying technology. I do this w/ ajax with a simple library called fauxjax today for xhrs and this allows me to stub in "return this json when this url is request via http GET". If I decide to switch from jQuery $.ajax to some other xhr library - no test rework is required because I wrote them agnostic of the tech.

I'm looking for this same "agnostic connection stub" for Websockets - does anything like this exist? Or is a full stub/spy/mock library like sinon the only approach worth looking at today?

I'm headed down the path of a simple monkey patch of window.WebSocket - just wanted to see if others have had such luck.

0

There are 0 best solutions below