我正在尝试模拟 $timeout 服务,我知道该怎么做,但是,我需要能够从我的模拟中调用原始 $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;
}]);
});
....
最佳答案
好的,我明白了。我需要使用装饰器(请参阅页面最后的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);
});
....
关于AngularJS - 单元测试 - 使用同一服务的模拟中的原始服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26999817/