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

大城市里の小女人 提交于 2019-12-01 14:30:25

问题


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.


回答1:


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.




回答2:


I found a way to do this:

/** Accept a prototype and return a full stub object */
function stub(obj, target) {
  var cls = (typeof obj == 'function') ? obj.prototype : obj;
  target = target || {};

  Object.getOwnPropertyNames(cls).filter(function(p){
    return typeof cls[p] == 'function';
  }).forEach(function(p) { target[p] = sinon.stub() });

  return cls.__proto__ ? stub(cls.__proto__, target) : target;
};

Use it like this:

var response = stub(http.ServerResponse);
response.getHeader.withArgs('X-Foo').returns('bob');
response.getHeader.withArgs('X-Bar').returns('barry');

console.log(response.getHeader('X-Foo')); // bob
console.log(response.getHeader('X-Bar')); // barry


来源:https://stackoverflow.com/questions/12025035/use-sinon-js-to-create-a-spy-object-with-spy-methods-based-on-a-real-construct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!