Question

I'm currently writing a NodeJS app and I'd like to write a test for a function. SinonJS seems to be the spy/stub/mock library of choice, but I can't seem to figure out how to stub a method on a function. For instance:

Lets say that I'm using a library called ExecSync. I want to stub the sh() method on that library from within my Spec, but it doesn't seem to work correctly. Would someone be kind enough to provide an example of stubbing a library method, from inside of a separate spec file?

To be clearer:

  • spec.js - This is where I'm writing my test.
  • util.js - This is where the method I'm testing exists. The method calls execSync.sh() and is included via npm and require().

Any help would be greatly appreciated.

Was it helpful?

Solution

Some code would be good, but usually this can be achieved like this (using mocha)

describe('A test', function() {
  beforeEach(function() {
    // what you want to stub is passed as a string
    sinon.stub(ExecSync, 'sh').yields(null,40);
  });

  afterEach(function() {
    ExecSync.restore();
  });

  it('has behaviour', function() {
    ExecSync.sh(function(err, res) {
      // err = null, res = 40
    });
  });
});

Another common practice when you cannot stub a dependency, is to write that dependency onto your module under test, such as

mymodule.ExecSync = function(arg) {
  ExecSync.sh(arg);
};

Then you can simply stub ExecSync on your module and never have to call the dependency at all.

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