如何在指令中对隔离范围进行单元测试

时间:2015-01-12 01:54:28

标签: angularjs unit-testing angularjs-directive jasmine karma-runner

我试图对一个简单的指令进行单元测试,但是范围中的变量总是未定义的。

指令Src代码:

.directive('ratingButton', ['$rootScope',


function($rootScope) {
      return {
          restrict: "E",
          replace: true,
          template: '<button type="button" class="btn btn-circle" ng-class="getRatingClass()"></button>',
          scope: {
              buttonRating: "="
          },
          link: function(scope, elem, attr) {
              scope.getRatingClass = function() {
                  if (!scope.buttonRating)
                      return '';
                  else if (scope.buttonRating.toUpperCase() === 'GREEN')
                      return 'btn-success';
                  else if (scope.buttonRating.toUpperCase() === 'YELLOW')
                      return 'btn-warning warning-text';
                  else if (scope.buttonRating.toUpperCase() === 'RED')
                      return 'btn-danger';
                  else if (scope.buttonRating.toUpperCase() === 'BLUE')
                      return 'btn-info';
              }
          }
      };
  }])

测试:

describe('Form Directive: ratingButton', function() {

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

    var scope,
        element;

    // Initialize the controller and a mock scope
    beforeEach(inject(function($compile, $rootScope) {
        scope = $rootScope.$new();

        //set our view html.
        element = angular.element('<rating-button button-rating="green"></rating-button>');
        $compile(element)(scope);
        scope.$digest();
    }));

    it('should return appropriate class based on rating', function() {
        //console.log(element.isolateScope());
        expect(element.isolateScope().buttonRating).toBe('green');
        expect(element.isolateScope().getRatingClass()).toBe('btn-success');

    });

});

我在另一个指令单元测试中使用了类似的代码,我通过元素属性传递值,它按预期工作。对于这个测试buttonRating始终未定义,不确定从哪里开始(我对Jasmine / Karma来说相当新)

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:25)

在测试启动时编译指令元素时,不要设置字符串green,而是在范围绑定上设置它。否则,它将在绑定范围上查找名称为green的scope属性的值,当然,在您的情况下未定义该值。

scope.buttonRating = 'green';

angular.element('<rating-button button-rating="buttonRating"></rating-button>')

尝试:

  // Initialize the controller and a mock scope
    beforeEach(inject(function($compile, $rootScope) {
        scope = $rootScope.$new();
        scope.buttonRating = 'green'; //<-- Here
        //set our view html.
        element = angular.element('<rating-button button-rating="buttonRating"></rating-button>');
        $compile(element)(scope);
        scope.$digest();
    }));

    it('should return appropriate class based on rating', function() {
        expect(element.isolateScope().buttonRating).toBe('green');
        expect(element.isolateScope().getRatingClass()).toBe('btn-success');

    });

<强> Plnkr