How to extend sandboxed sinon with custom methods and fields

482 Views Asked by At

Suppose I want extend sinon by adding my own special stub: I can just write:

sinon.specialStub = function() {
    return this.stub().returns('SPECIAL');
};

Or I can use sinon.extend and write something like:

    sinon.extend(sinon, {
      specialStub: function() {
        return this.stub().returns('SPECIAL');
      }
    });

which will do basically the same.

Everything will work just as expected but invoking this method with var sandbox = sinon.sandbox.create(); will fail.

Here's the only known workaround I can think of:

 var sandbox =  sinon.extend(sinon.sandbox.create(), {
      specialStub: function() {
        return this.stub().returns('SPECIAL');
      }
 });

The quesion is - does any one know how to extend sinon and to see those extended methods in sandbox?

1

There are 1 best solutions below

0
On

The only way I know of is to add the method to sinon.collection.

sinon.collection.specialStub = function() { return this.stub().returns('Special'); }
var sandbox = sinon.sandbox.create();
console.log(sandbox.specialStub);

Might consider asking sinon's maintainer to find out if that's brittle because it taps into things they consider internal to the library.