Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to mock rabbit.js #85

Open
tobias-neubert opened this issue Dec 18, 2014 · 1 comment
Open

How to mock rabbit.js #85

tobias-neubert opened this issue Dec 18, 2014 · 1 comment

Comments

@tobias-neubert
Copy link

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
Copy link

@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();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants