你如何刺探AngularJS与茉莉花$超时? [英] How do you spy on AngularJS's $timeout with Jasmine?
问题描述
我试图窥探$超时,这样我可以验证它没有被调用。具体来说,我的生产code(见下文)调用$超时作为一个函数,而不是对象:
I am trying to spy on $timeout so that I can verify that it has not been called. Specifically, my production code (see below) calls $timeout as a function, not an object:
$timeout(function() { ... })
而不是
$timeout.cancel() // for instance
茉莉花,但是,需要在被窥探的对象,像这样的:
Jasmine, however, requires an object to be spied upon, like this:
spyOn(someObject, '$timeout')
我不知道什么'someObject'是虽然。
I don't know what 'someObject' would be though.
我使用的角度嘲笑,如果让任何区别。
I am using Angular mocks, if that makes any difference.
编辑:相关生产code我试图测试如下:
The relevant production code I'm trying to test looks like this:
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
}
在具体的测试场景中我试图断言$超时从未被调用。
In the specific test scenario I am trying to assert that $timeout was never called.
编辑2:指定清楚,我使用$超时作为一个函数,而不是对象
Edit 2: Specified clearly that I am using $timeout as a function, not an object.
推荐答案
在角 $超时
是执行/调用一个函数的服务。请求为间谍 $超时
有点奇怪在于它是什么做的是Y中给定的时间执行点¯x功能的情况。我会做窥探这个服务是模拟超时功能,在您的控制器像它注入:
In angular $timeout
is a service that executes/calls a function. The request to "spy" $timeout
is a bit odd being the case that what it is doing is executing X function in Y given time. What I would do to spy this services is to "mock" the timeout function and inject it in your controller something like:
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);
...
这篇关于你如何刺探AngularJS与茉莉花$超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!