Skip to content

Instantly share code, notes, and snippets.

@abloom
Forked from x1024/gist:794143
Created April 8, 2011 18:01
Show Gist options
  • Save abloom/910391 to your computer and use it in GitHub Desktop.
Save abloom/910391 to your computer and use it in GitHub Desktop.
var http = require('http'),
should = require('should'),
io = require('socket.io'),
decode = require('.npm/socket.io/0.6.8/package/lib/socket.io/utils').decode,
encode = require('.npm/socket.io/0.6.8/package/lib/socket.io/utils').encode,
WebSocket = require('.npm/socket.io/0.6.8/package/support/node-websocket-client/lib/websocket.js').WebSocket;
exports['Socket.IO mocking'] = function(assert){
var _server = require('http').createServer(function(){});
// A mock client object.
var _client;
// Used as an easy way to know when to shut the server down.
var messages_to_receive = 4;
var port = 5000 // Any number will do
_server.listen(port, function(){
// When this function is called, the server will be started.
// We can now write some mocked-out client code to connect to it.
// This is the equivalent to "new io.Socket(...)" in the browser
// What we send here will be received in the server as if it were sent from a browser
_client = new WebSocket('ws://localhost:' + port + '/socket.io/websocket', 'borf');
_client.messages = [];
// The encode/decode parts are not obvious - do not forget them :) :)
_client.onmessage = function(ev) {
// These are the messages received at the "client"
this.messages.push(decode(ev.data)[0])
if (--messages_to_receive == 0)
close();
};
// This part is optional
_client.onopen = function(){
_client.send(encode('Test Message'));
};
});
// Init the server-side socket as we always do.
// This is the same kind of code as in the chat tutorial.
// In here you can put your actual Socket.IO handler on the server
// (which we will be testing).
var _socket = io.listen(_server);
_socket.on('connection', function(conn){
conn.on('message', function(msg){
msg.should.equal('Test Message');
if (--messages_to_receive == 0)
close();
// This part is optional
conn.send('From server');
})
// This part is optional
_socket.broadcast("Broadcast message");
});
var close = function() {
_client.messages.length.should.equal(3);
// _client.messages[0] is always the sessionId of the client.
_client.messages[1].should.equal("Broadcast message");
_client.messages[2].should.equal("From server");
_client.close();
_server.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment