Stubbing a function that does not belong to an object

1,530 views
Skip to first unread message

Kier Borromeo

unread,
Apr 15, 2015, 3:30:30 PM4/15/15
to sin...@googlegroups.com
I'd like to stub a mere function that doesn't belong to an object. Is this possible? sinon.stub's api seems to accept only an object, and a property name (the fn).

For example:

var jwt = function () {
  // transform stuff
}

var thingToBeTested = function(x) { 
  return jwt(x);
}

describe('Thing', () => {
  it('should return a jwt-ed x', () => {
    expect(thingToBeTested(5)).to.equal(/* jwt-ed */)
  });
});

Jonathon Creenaune

unread,
Apr 15, 2015, 5:03:04 PM4/15/15
to sin...@googlegroups.com
You can definitely create a standalone stub using


--
You received this message because you are subscribed to the Google Groups "Sinon.JS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sinonjs+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Kier Borromeo

unread,
Apr 15, 2015, 7:19:29 PM4/15/15
to sin...@googlegroups.com
I think I should've stated that I'm using CommonJS `require` to get `jwt`.

Jonathon Creenaune

unread,
Apr 15, 2015, 8:28:38 PM4/15/15
to sin...@googlegroups.com
In that case you have a couple of options:

- refactor your thingToBeTested code to be a factory. ie, your module would be a factory that takes the jwt function instead of require'ing jwt from inside thingToBeTested:

// thingToBeTested.js
// note: does not require jwt.js
module.exports = function thingToBeTestedFactory(jwt) {
  return function thingToBeTested(x) {
    return jwt(x);
  };
}

in your code:

// app-setup.js
var jwt = require('./jwt.js'),
  thingToBeTested = require('./thingToBeTested.js')(jwt);

in your test:

// test-thingToBeTested.js
var jwtStub = sinon.stub();
var thingToBeTested = require('./thingToBeTested.js')(jwtStub);


- alternatively, I'm not sure if there's a way to stub require() deps in CommonJS. In the browser / AMD, I've used Squire.js https://github.com/iammerrick/Squire.js/ to mock out modules.



Travis Kaufman

unread,
Apr 15, 2015, 9:46:07 PM4/15/15
to sin...@googlegroups.com
There's also rewire (https://github.com/jhnns/rewire) which has been extremely handy in the past for me!

Morgan Roderick

unread,
Apr 16, 2015, 7:16:52 AM4/16/15
to sin...@googlegroups.com
If you're not going with the dependency injection route, you should check out

https://github.com/thlorenz/proxyquire

/Morgan
Reply all
Reply to author
Forward
0 new messages