【问题标题】:Unit Test Directive Controllers in AngularJSAngularJS 中的单元测试指令控制器
【发布时间】:2014-02-06 21:28:21
【问题描述】:

我正在尝试完全了解如何使用 Jasmine 在 AngularJS 中测试指令。目前,我有一个设置如下所示的指令:

.directive('myDirective', function() {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: {
          title:'=',
          state:'@'
        },
        templateUrl: 'myHtml.tpl.html',
        controller: function ($scope) {
          // Business Logic Specific to the Directive goes in here
        }
    };
})

正如上面的代码 sn-p 所示,我的指令在指令定义内有一个控制器。我试图测试的具体指令相当复杂。指令中的控制器有超过 200 行代码。我试图弄清楚如何围绕这个控制器的内容编写单元测试。目前我有以下:

describe('myApp', function () {
    var $scope;

    beforeEach(module('myApp'));
    beforeEach(inject(function ($controller, $rootScope) {
        $scope = $rootScope.$new();
    }));

    it('should create my directive', inject(function ($rootScope, $compile, $log) {
      var card = angular.element('<my-directive></my-directive>');
      $compile(card)($rootScope);
      $scope.$digest();

      expect($log.assertEmpty).not.toThrow();
    }));
});

上面的单元测试测试指令本身的创建。但是,我不知道如何在指令中测试控制器。有没有办法做到这一点?如果有,怎么做?

谢谢!

【问题讨论】:

    标签: unit-testing angularjs controller jasmine directive


    【解决方案1】:

    您可以使用以下代码测试您的控制器:

    describe('myApp', function () {
    var $scope;
    
    beforeEach(module('myApp'));
    beforeEach(inject(function ($controller, $rootScope) {
        $scope = $rootScope.$new();
        var card = angular.element('<my-directive></my-directive>');
        $compile(card)($rootScope);
        $scope.$digest();
        controller = element.controller
    }));
    
    it('should create my directive', inject(function ($rootScope, $compile, $log) {
        //TRY YOUR BUSINESS LOGIC TESTS HERE
        //$scope.yourFunction(yourArgs...);
        //expect($scope.yourVars).toSomething
    }));
    

    });

    【讨论】:

    • 如果控制器正在注入服务,有没有办法测试它?还是仅适用于传入所有信息的“哑”指令?
    • 应该是controller = card.controller 吗?
    【解决方案2】:

    据我所知,有一种用于分离指令控制器的语法,例如:

    .directive('myDirective', function() {
        return {
            restrict: 'E',
            transclude: true,
            replace: true,
            scope: {
              title:'=',
              state:'@'
            },
            templateUrl: 'myHtml.tpl.html',
            controller: 'MyDirectiveCtrl as ctrl'
        };
    })
    

    并将其注册为常规控制器

    .controller("MyDirectiveCtrl", function($scope) {})
    

    因此,如果您这样做,那么您可以使用 $controller 创建此控制器并愉快地进行测试。

    【讨论】:

      猜你喜欢
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      相关资源
      最近更新 更多