squaremo / rabbit.js

Messaging in Node.JS made easy using RabbitMQ
Other
1.52k stars 142 forks source link

How to mock rabbit.js #85

Open tobias-neubert opened 9 years ago

tobias-neubert commented 9 years ago

Hi

this might be a little off topic but nevertheless I give it a try. I am using rabbit.js in a node.js project and I really would like to implement some unit tests for my classes that use rabbit.js. I've spend a whole day to play around with jasmine-node, rewire and sinon but I am totally lost. Maybe it is because I've never tried to implement unit tests for asynchronous code and maybe it is because I am not that experienced in programming java script. Most likely it is because of both :-)

Can anyone recommend a way to implement unit tests for code like this one? How would you test, if calling bar() results in publishing a message?

Thankful for any hints, Tobias

var rabbitjs = require('rabbit.js');

function Foo(rabbitHost, rabbitPort) {
    this.rabbit = rabbitjs.createContext('amqp://' + rabbitHost + ':' + rabbitPort);
};

Foo.prototype.bar = function () {
    var self = this;
    this.rabbit.on('ready', function () {
        var socket = self.rabbit.socket('PUBLISH');
        socket.end('hello-rabbit', 'Here I am');
    });
};

module.exports = Foo;
realistschuckle commented 9 years ago

@tobias-neubert I would change your API, a little.

function Foo(context) {
  this.context = context;
}

Foo.prototype.bar = function () {
  var self = this;
  this.context.on('ready', function () {
    var socket = self.context.socket('PUBLISH');
    socket.end('hello-rabbit', 'Here I am');
  });
};

module.exports = Foo;

Then, I could test it with (shameless plug) something like nodemock.

var nodemock = require('nodemock');
var ctrl = {};
var frabbit = nodemock.mock('on').takes('ready', function () {}).ctrl(1, ctrl);
frabbit.mock('socket').takes('PUBLISH');
frabbit.mock('end').takes('hello-rabbit', 'Here I am');

var Foo = require('./foo'); // Your file
var foo = new Foo(frabbit);
foo.bar();

ctrl.trigger(10, 20); // triggers the callback of the "on" method
frabbit.assert();