使用sinon.js创建一个“间谍对象".基于真正的构造函数/原型的间谍方法 [英] Use sinon.js to create a "spy object" with spy methods based on a real constructor/prototype

查看:126
本文介绍了使用sinon.js创建一个“间谍对象".基于真正的构造函数/原型的间谍方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sinon.js作为在我的Mocha测试中解决依赖项的方法.我喜欢间谍"方法而不是经典的模拟方法,因为与经典的模拟对象相比,间谍的内省似乎更清晰,并且具有更大的灵活性.

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.

也就是说,我不知道在为整个对象创建测试间谍程序时是否使用不正确.假设我有一个测试依赖项,上面有4个方法,并且我想对每个方法进行存根处理并对其中的一个或两个进行断言.目前,我正在这样做:

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()
};

然后我只问类似spyObj.aMethod.calledWith(a, b, c)的事情.

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

有没有比重复测试套件本身中的方法名称更好的方法来模拟整个类?看起来sinon.stub()尝试遍历给定对象的所有成员,但这似乎不能作为在更现代的JS运行时(例如V8)中获取大多数对象的所有方法的一种方式,除非该对象实际上是可数的.它还尝试猴子修补实际对象,而不是返回等效对象,这在某种程度上是不可取的.我只需要一个符合接口的对象,但表现得像一个空对象,除非我另有说明.

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);

如何创建Node.js中的构造函数/原型的所有方法,以便像上面那样包装?

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

与测试大量方法(我尝试将其限制为一种,或者一推二)相比,这更多的是讲究逻辑.例如,可能执行不必要的I/O或执行其他复杂装置的事情.

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.

推荐答案

从Sinon 1.6.0开始,您可以执行以下操作:

Starting with Sinon 1.6.0 you can do:

var stub = sinon.createStubInstance(MyClass)

存根API部分 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆