我正在尝试模拟$ timeout服务,我知道该怎么做,但是,我需要能够从我的模拟中调用ORIGINAL $ timeout服务。但是,它最终会出现堆栈溢出,递归调用自身......
describe("myUnitTest", function () {
var $compile;
var $rootScope;
var $window;
var $timeout;
var timerTriggeredCount;
beforeEach(function () {
module("myModuleBeingTested", function ($provide) {
$provide.value("$timeout", fakeTimeout);
function fakeTimeout(func) {
timerTriggeredCount++;
return $timeout(func, 1, false); // need this to call the original $timeout service
}
fakeTimeout.cancel = function(timer) {
$timeout.cancel(timer); // need this to call the original $timeout servic
}
});
inject(["$compile", "$rootScope", "$window", "$timeout", function (c, rs, w, t) {
$compile = c;
$rootScope = rs;
$window = w;
$timeout = t;
}]);
});
....
答案 0 :(得分:2)
好的,我明白了。我需要使用装饰器(请参阅页面最后的here):
describe("myUnitTest", function () {
var $compile;
var $rootScope;
var $window;
var $timeout;
var timerTriggeredCount;
beforeEach(function () {
module("myModuleBeingTested", function ($provide) {
var fakeTimeoutDecorator = [
"$delegate", function ($delegate) {
var oldTimeout = $delegate;
var fakeTimeout = function (fn, delay, invokeApply) {
return oldTimeout(function() {
timerTriggeredCount++;
fn();
}, 1, invokeApply);
};
for (var prop in oldTimeout) {
fakeTimeout[prop] = oldTimeout[prop];
}
return fakeTimeout;
}
];
$provide.decorator("$timeout", fakeTimeoutDecorator);
});
....