AngularJS,防止控制器上的init方法在茉莉花测试期间启动

mla*_*her 9 initialization jasmine angularjs

我有一个控制器,在实例化时启动了init()方法.它做了很多对我的应用程序在实时环境中有用的东西,但这与我的单元测试间谍混淆了.

有没有办法在单元测试环境中实例化控制器时阻止其调用?或者也许是一种在webapp上下文中自动调用它而不在控制器代码末尾显式调用init()的方法?

pko*_*rce 13

在没有看到实时代码示例的情况下提供精确指导有点困难(这就是为什么提供一个具有Jasmine测试模板的插件通常是一个好主意)但听起来你的init方法执行一些应该是的设置逻辑根据环境的不同而不同.如果是这样,前进的方法是将这个初始化逻辑封装到专用服务中并在测试期间模拟这个服务(这正是@Joe Dyndale所建议的).

如果您的控制器如下所示:

app.controller('MainCtrl', function($scope) {
  $scope.init = function() {
    //something I really don't want to call during test
    console.log("I'm executing");
  };
});
Run Code Online (Sandbox Code Playgroud)

它可以重构为:

app.factory('InitService', function() {
  return {
    init = function() {
      //something I really don't want to call during test
      console.log("I'm executing");
    }
  };
});

app.controller('MainCtrl', function($scope, InitService) {
  InitService.init();
});
Run Code Online (Sandbox Code Playgroud)

然后用模拟测试看起来像这样:

describe('Testing an initializing controller', function() {
  var $scope, ctrl;

  //you need to indicate your module in a test
  beforeEach(module('plunker'));
  beforeEach(module(function($provide){
    $provide.factory('InitService', function() {
      return {
        init: angular.noop
      };
    });
  }));
  beforeEach(inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();
    ctrl = $controller('MainCtrl', {
      $scope: $scope
    });
  }));

  it('should test sth on a controller', function() {
    //
  });
});
Run Code Online (Sandbox Code Playgroud)

最后这里是plunker中的实时代码