如何使用angularJS-karma-jasmine测试指令的控制器?

时间:2014-12-03 05:03:38

标签: javascript angularjs angularjs-directive jasmine karma-jasmine

目标:

waCarousel指令范围变量编写通过测试:self.awesomeThings。当self.awsomeThings.length.toBe(3)为真时,期望此测试通过吗?

问题:

如何正确编写此测试?而是如何注入指令控制器?


指令:

angular.module('carouselApp')
    .directive('waCarousel', function() {
        return {
            templateUrl: '../../../views/carousel/wa.carousel.html',
            controller: function($scope) {
                var self = this;

                self.awesomeThings = [1, 2, 3];

                return $scope.carousel = self;
            }
        }
    });

单元测试:

describe('waCarousel Unit', function() {
  // am I missing a $controller & namespace variable init?
   var $compile,
      $rootScope;


  // Load the myApp module, which contains the directive
  beforeEach(module('carouselApp'));

  // Store references to $rootScope and $compile and $controller
  // so they are available to all tests in this describe block
  beforeEach(inject(function(_$compile_, _$rootScope_, _$controller_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $compile = _$compile_;
    $rootScope = _$rootScope_;
    $controller = _$controller_;
     //   WaCarouselCtrl = $controller('WaCarouselCtrl', {
     //       $scope: scope
     //   });
  }));

  it('should have a list of awesomeThings', function() {
    // This wont pass       
    expect(scope.awesomeThings.length).toBe(3);
  });
});

这就是我对典型视图而不是指令的做法:

describe('Controller: MainCtrl', function() {

    // load the controller's module
    beforeEach(module('carouselApp'));

    var MainCtrl,
        scope;

    // Initialize the controller and a mock scope
    beforeEach(inject(function($controller, $rootScope) {
        scope = $rootScope.$new();
        // !!*** this is how I would inject the typical controller of a view **!! //
        MainCtrl = $controller('MainCtrl', {
            $scope: scope
        });
    }));

    it('should attach a list of awesomeThings to the scope', function() {
        expect(scope.awesomeThings.length).toBe(3);
    });
});

如何合并这两个概念,以便我可以期待self.awesomeThings.length).toBe(3)

更新: enter image description here

1 个答案:

答案 0 :(得分:13)

Compile元素,在调用$digest()之后,您将可以访问包含carousel对象awesomeThings数组的范围:

describe('waCarousel Unit', function() {
    var scope;

    beforeEach(module('carouselApp'));
    beforeEach(inject(function($rootScope, $compile) {
        var element = '<test></test>';

        scope = $rootScope.$new();

        element = $compile(element)(scope);
        scope.$digest();
    }));

    it('should have a list of awesomeThings', function() {    
        expect(scope.carousel.awesomeThings.length).toBe(3);
    });
});

此外,这里有一些有用的链接指向角度测试指令: