Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nicolab/8620221 to your computer and use it in GitHub Desktop.
Save Nicolab/8620221 to your computer and use it in GitHub Desktop.
// Example test that stubs out node.js net.Socket.write() calls
// Using Mocha to drive: http://visionmedia.github.com/mocha/
// sinon.js for stubs/mocks/spies: http://sinonjs.org
// should.js for assertions: https://github.com/visionmedia/should.js
var sinon = require('sinon')
, should = require('should')
, net = require('net')
describe('Example Stubbing net.Socket', function() {
it ("should stub net.Socket.write( ) and echo back what was written", function(done) {
var socket = new net.Socket({});
var stub = sinon.stub(socket, 'write', function (data, encoding, cb) {
var args = stub.args;
// this will echo whatever they wrote
if (args.length > 0)
this.emit('data', stub.args[stub.callCount - 1][0]);
});
socket.on('data', function(data) {
data.should.eql('foo');
// test is done or it will timeout and fail
done();
});
socket.write('foo');
});
});
// Example test that spies on SocketStream.publish.channel() calls
// Using Mocha to drive: http://visionmedia.github.com/mocha/
// sinon.js for stubs/mocks/spies: http://sinonjs.org
// should.js for assertions: https://github.com/visionmedia/should.js
var sinon = require('sinon')
, should = require('should')
, ss = require('socketstream').start();
describe("Spying on SocketStream for testing", function() {
var spy;
beforeEach( function(done) {
spy = sinon.spy(ss.publish, 'channel');
done();
});
afterEach( function(done) {
spy.restore(ss.publish);
spy.reset();
done();
});
// here you'd be testing your code which triggers pub/sub
// the spy allows you to assert that it was or was not triggered
it("should allow me to spy on publish calls", function(done) {
// publish foo event once
ss.publish.channel('foo', 'fooEvent', 'fooMessage');
ss.publish.channel.called.should.be.true;
// publish bar event twice
ss.publish.channel('bar', 'barEvent', 'barMessage');
ss.publish.channel.calledTwice.should.be.true;
ss.publish.channel('bar', 'barEvent2', 'barMessage');
ss.publish.channel.calledThrice.should.be.true;
ss.publish.channel.withArgs('foo').calledOnce.should.be.true;
ss.publish.channel.withArgs('bar').calledTwice.should.be.true;
done();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment