Yng*_*sen 6 unit-testing spy jasmine angularjs
我试图窥探$ timeout,以便我可以验证它没有被调用.具体来说,我的生产代码(见下文)将$ timeout称为函数,而不是对象:
$timeout(function() { ... })
Run Code Online (Sandbox Code Playgroud)
并不是
$timeout.cancel() // for instance
Run Code Online (Sandbox Code Playgroud)
然而,Jasmine需要一个物体被监视,如下所示:
spyOn(someObject, '$timeout')
Run Code Online (Sandbox Code Playgroud)
我不知道'someObject'会是什么.
我正在使用Angular模拟,如果这有任何区别.
编辑:我正在尝试测试的相关生产代码如下所示:
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
}
Run Code Online (Sandbox Code Playgroud)
在特定的测试场景中,我试图断言永远不会调用$ timeout.
编辑2:明确指出我使用$ timeout作为函数,而不是对象.
小智 7
陷入同样的问题,并最终用间谍装饰$ timeout服务.
beforeEach(module(function($provide) {
$provide.decorator('$timeout', function($delegate) {
return sinon.spy($delegate);
});
}));
Run Code Online (Sandbox Code Playgroud)
写了更多关于为什么这里有用的信息.
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);
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5736 次 |
| 最近记录: |