我正试图监视$timeout,以便验证它是否未被调用。具体来说,我的生产代码(见下文)调用$timeout作为一个函数,而不是一个对象:
$timeout(function() { ... })
而不是
$timeout.cancel() // for instance
然而,Jasmine需要一个被监视的对象,就像这样:
spyOn(someObject, '$timeout')
不过我不知道"someObject"会是什么。
我使用的是Angular mock,如果这有什么不同的话。
编辑:我试图测试的相关生产代码如下:
EventHandler.prototype._updateDurationInOneSecondOn = function (call) {
var _this = this;
var _updateDurationPromise = this._$timeout(function () {
call.duration = new Date().getTime() - call.startTime;
_this._updateDurationInOneSecondOn(call);
}, 1000);
// ... more irrelevant code
}
在特定的测试场景中,我试图断言$timeout从未被调用过。
编辑2:明确指出我使用$timeout作为函数,而不是对象。
遇到了同样的问题,最终用间谍装饰了$timeout服务。
beforeEach(module(function($provide) {
$provide.decorator('$timeout', function($delegate) {
return sinon.spy($delegate);
});
}));
在这里写下更多关于它为什么有效的内容。
在angular中,$timeout
是一个执行/调用函数的服务。对"侦察"$timeout
的请求有点奇怪,因为它正在做的是在Y给定的时间内执行X函数。我要做的是监视这些服务是"模拟"超时功能,并将其注入您的控制器中,类似于:
it('shouldvalidate time',inject(function($window, $timeout){
function timeout(fn, delay, invokeApply) {
console.log('spy timeout invocation here');
$window.setTimeout(fn,delay);
}
//instead of injecting $timeout in the controller you can inject the mock version timeout
createController(timeout);
// inside your controller|service|directive everything stays the same
/* $timeout(function(){
console.log('hello world');
x = true;
},100); */
var x = false; //some variable or action to wait for
waitsFor(function(){
return x;
},"timeout",200);
...
此代码适用于我的
var element, scope, rootScope, mock = {
timeout : function(callback, lapse){
setTimeout(callback, lapse);
}
};
beforeEach(module(function($provide) {
$provide.decorator('$timeout', function($delegate) {
return function(callback, lapse){
mock.timeout(callback, lapse);
return $delegate.apply(this, arguments);
};
});
}));
describe("when showing alert message", function(){
it("should be able to show message", function(){
rootScope.modalHtml = undefined;
spyOn(mock, 'timeout').and.callFake(function(callback){
callback();
});
rootScope.showMessage('SAMPLE');
expect(rootScope.modalHtml).toBe('SAMPLE');
});
});