AngularJS - 单元测试 - 使用同一服务的模拟中的原始服务?

标签 angularjs unit-testing jasmine karma-runner

我正在尝试模拟 $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/

相关文章:

javascript - PHP 脚本不接受来自具有 AngularJS 脚本的客户端的 GET/POST 数据

angularjs - 将焦点设置到 AngularJS 中的第一个无效表单元素

javascript - 在 Angular.js 应用程序中进行事件驱动开发的最佳实践是什么?

c# - 对继承类的最小起订量测试总是返回 null

javascript - jest.fn() 被多次调用

jasmine - 在 VueJS : Unknown custom element: <router-link> 中运行测试时出错

javascript - Jasmine 规范基准测试

javascript - 预期 [ ] 为 [ ] Jasmine,如何检查空数组

javascript - Angular : Access scope from within &lt;script&gt; tag

c++ - 如何在调试版本中测试断言,但在发布版本中返回值?