使用 sinonjs 测试方法调用的上下文
Test the context of a method call using sinonjs
>我有一个类,我在初始化时绑定了一个方法,如下所示 -
function MyClass() {
this.onHttpCallback = _.bind(onHttpCallback, this);
}
function onHttpCallback(){
//...
}
如何测试调用onHttpCallback
时是否总是使用 MyClass 的对象作为上下文进行调用?
我正在使用 sinon.js 来模拟,以下代码不起作用 -
it('should be binded', function () {
//ctrl is an object of MyClass
var dummy_obj = {};
var spy = sinon.spy(ctrl.onHttpCallback);
spy.call(dummy_obj);
spy.alwaysCalledOn(ctrl).should.be.ok;
});
更新根据以下答案中的注释,似乎无法测试方法的绑定。
我对问题的看法
//Source.js
function MyClass() {
}
MyClass.prototype.init = function(){
this.onHttpCallback = _.bind(MyClass.onHttpCallback, this);
}
MyClass.onHttpCallback(){
//...
}
//Test.js
it('should bind onHttpCallback', function () {
sinon.spy(_, 'bind');
ctrl.init();
_.bind.calledWith(ctrl.constructor.onHttpCallback, ctrl).should.be.ok;
_.bind.restore();
});
像魅力一样工作!
如果您
想知道为什么即使您之前明确将其绑定为MyClass
,this
也会更改,那是因为您在间谍上使用call
dummy_obj
。
间谍包装原始函数,因此它没有该函数绑定的概念。它仍然会在包装函数上接受不同的绑定,然后尝试使用该this
调用原始绑定,然后被原始函数忽略。
var context = {foo: 'bar'};
var original = _.bind(function () { console.log(this); }, context);
var spy = function (original) {
var spyFn = function () {
var _this = this;
spyFn.calledOn = function (ctx) { return ctx === _this; };
return original.apply(this, arguments);
};
return spyFn;
};
var originalSpy = spy(original);
// Will call the spyFn with a different `this`, but will not affect the original binding
originalSpy.call({something: 'else'});
>> {foo: 'bar'}
// Since the spy cannot know the original binding, it will think the assumption is false.
originalSpy.calledOn(context) === false;
相关文章:
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 是否可以在不更改上下文的情况下调用函数.apply
- 调用$.each()函数时上下文发生变化
- 如何更改对 javascript 属性的调用的范围/上下文
- API Google Maps Javascript在上下文菜单中调用事件侦听器
- Ember添加了对转换调用上下文(路由/控制器)的检查
- 使用数组-apply()中的参数调用函数,但不使用上下文参数
- 函数调用上下文
- 显示和隐藏上下文菜单时的 Jstree 调用事件
- 在 mongo map 中调用外部 javascript 函数(对象)或减少上下文的可能方法
- Chrome getSelection如果从上下文菜单调用则不起作用
- Java 脚本 eval() 函数属于哪个对象?此外,在调用 eval() 函数时传递执行上下文
- 第二次调用主干时在回调中丢失上下文
- 在mootools中调用没有上下文的.fireEvent()
- 在 $http.get 调用中获取服务上下文
- 角度组件语法,回调函数使用错误的上下文调用
- Firefox XUL从内容上下文调用函数
- Javascript:跟踪函数父对象层次结构,以便从窗口上下文调用它
- 使用上下文调用 bind()
- 从DOM上下文调用casperjs捕获(求值)