Question

So I'm trying to mock or stub the call to growl library. When required, it returns a function that will fire a growl notification when invoked. I can't figure out how to mock or stub this out within my tests.

This is what I've tried so far:

/* /lib/some_code.js */
var growl = require('growl');
exports.some_func = function() { 
  growl('A message', { title: 'Title' }); 
};

(Note: I'm using sinon-chai for my assertions)

/* /test/some_code.js */
var growl = require('growl')
  , some_code = require('../lib/some_code');

describe('Some code', function() {
  it('sends a growl notification', function(done) {
    var growlStub = sinon.stub(growl);
    some_code.some_func();
    growlStub.should.have.been.called;
    done();
  });
});
Was it helpful?

Solution

So I've come up with a solution that seems to work, though I personally find it a little unclean.

The code under test just needs to export it's dependency on growl and use the function from the exports internally.

// Code under test
exports.growl = require('growl');
exports.some_func = function() {
  exports.growl('message', { title: 'Title' });
};

// Test
var some_code = require('../lib/some_code');   
describe('Some code', function() {
  it('sends a growl notification', function(done) { 
    var growlStub = sinon.stub(some_code, 'growl');
    some_code.some_func();
    growlStub.should.have.been.called;
    done();
  });
});

If someone has a better solution, I'd love to see it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top