使用 sinon 监视 javascript 中的构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14800428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spying on a constructor in javascript with sinon
提问by billy
I am trying to create a spy on a constructor, and see if it gets called -- below are my tests. I'm using sinon-chai so the syntax is valid, but both tests fail.
我试图在构造函数上创建一个间谍,看看它是否被调用——下面是我的测试。我正在使用 sinon-chai,所以语法是有效的,但两个测试都失败了。
var foo = function(arg) {
};
var bar = function(arg) {
var baz = new foo(arg);
};
it('foo initialized inside of this test', function() {
var spy = sinon.spy(foo);
new foo('test');
expect(spy).to.be.called;
expect(spy).to.be.calledWith('test');
});
it('foo initialized by bar()', function() {
var spy = sinon.spy(foo);
bar('test');
expect(spy).to.be.called;
expect(spy).to.be.calledWith('test');
});
采纳答案by billy
The problem is that Sinon doesn't know what reference to spy on, so the solution is to either use an object i.e. sinon.spy(namespace, 'foo')
or override the reference yourself foo = sinon.spy(foo)
.
问题在于,Sinon 不知道要监视什么引用,因此解决方案是使用对象 iesinon.spy(namespace, 'foo')
或自己覆盖引用foo = sinon.spy(foo)
。
回答by stckvflw
Considering your constructor is bound to 'window' which means that if you open developer console on your browser, you should be able to intantiate an object by using the related function/constructor as such:
考虑到您的构造函数绑定到“window”,这意味着如果您在浏览器上打开开发人员控制台,您应该能够使用相关的函数/构造函数来实例化一个对象,如下所示:
var temp = new FunctionName();
If so actual working code could be:
如果是这样,实际工作代码可能是:
var jamesBond = sinon.spy(window, 'FunctionName');
var temp = new FunctionName(args);
expect(jamesBond.called).to.be.equal(true);
回答by villasv
In case you want to use this on Node, @stckvflw's answer can be adapted assuming you know the namespace of the constructor like @billy mentioned. For JS built-in classes you'll probably be right to assume that they live in global
.
如果你想在 Node 上使用它,@stckvflw 的答案可以调整,假设你知道像 @billy 提到的构造函数的命名空间。对于 JS 内置类,您可能正确地假设它们位于global
.
A concrete example using chai-spies
to freeze the Date
object (equivalent of creating a stub
with Sinon):
一个使用chai-spies
冻结Date
对象的具体例子(相当于stub
用Sinon创建一个):
const moment = new Date();
chai.spy.on(global, 'Date', () => moment);