Use sinon.js to create a "spy object" with spy methods based on a real constructor/prototype

d11wtq picture d11wtq · Aug 19, 2012 · Viewed 12.9k times · Source

I'm using sinon.js as a way to stub out dependencies in my Mocha tests. I prefer the 'spy' approach over a classic mock approach, as the introspection of the spy seems clearer and affords more flexibility than the somewhat backward-thinking with classic mock objects.

That said, I wonder if I'm using it incorrectly when it comes to creating test spies for whole objects. Let's say I have a test dependency that has 4 methods on it and I want to stub each of those methods and make assertions on one or two of them. Currently I'm doing this:

var spyObj = {
  aMethod: sinon.spy(),
  otherMethod: sinon.spy(),
  whatever: sinon.spy()
};

Then I just ask things like spyObj.aMethod.calledWith(a, b, c).

Is there a better way to mock out an entire class than repeating the names of the methods in the test suite itself? It looks like sinon.stub() tries to iterate over all the member of a given object, but that doesn't seem to work as a way to get all methods for most objects in more modern JS runtimes, like V8, unless the object is actually something enumerable. It also tries to monkey patch the actual object, rather than returning an equivalent one, which is somewhat undesirable. I just need an object that conforms to an interface, but behaves like a null object, unless I tell it otherwise.

It would be good to be able to do something like:

var spyObject = sinon.spy(MyClass.prototype);

How does one find all methods of a constructor/prototype in Node.js, in order to make a wrapper like the above?

This is more about stubbing out logic, than testing invocations on lots of methods (which I try to limit to one, or at a push two). For example, things that might do unwanted I/O, or require additional complex fixtures if executed.

Answer

tfischbach picture tfischbach · Sep 26, 2013

Starting with Sinon 1.6.0 you can do:

var stub = sinon.createStubInstance(MyClass)

See documentation for sinon.stub in Stub API section or the source.