如何在指令中对独立范围进行单元测试

How can I unit test isolated scope in directive

我正在尝试对一个简单的指令进行单元测试,但作用域中的变量始终未定义。

指令源代码:

.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 很陌生)

任何帮助都会很棒!

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

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