【问题标题】:AngularJS - unit tests - using original service from mock of same service?AngularJS - 单元测试 - 使用来自同一服务模拟的原始服务?
【发布时间】: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


【解决方案1】:

好的,我明白了。我需要使用装饰器(请参阅页面末尾的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);

  });

....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多