【发布时间】:2014-11-18 17:01:45
【问题描述】:
我正在尝试模拟 $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;
}]);
});
....
【问题讨论】:
-
为什么需要调用真正的超时时间?我怀疑你最好在测试中调用$timeout.flush 来测试在$timeout 之后运行的东西。
-
@MichalCharemza 我希望能够 1)修改超时的延迟,这样它就不会使单元测试变慢;2)我想在每次触发超时时增加一个计数器。
-
对于 1) 你应该能够在你的测试中使用 $timeout.flush,这将使你的测试同步并且避免需要将任何东西传递给真正的 $timeout。它甚至可能会稍微快一点,因为它不会根据您的解决方案等待 1 毫秒 :-)
标签: angularjs unit-testing jasmine karma-runner