angularjs – 如何单元测试指令中的隔离范围

前端之家收集整理的这篇文章主要介绍了angularjs – 如何单元测试指令中的隔离范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图单元测试一个简单的指令,但范围中的变量总是未定义的.

指令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总是不确定不知道从哪里去(我是相当新的茉莉/羯磨)

任何帮助将是伟大的!

当您在启动测试时编译指令元素时,而不是设置字符串绿色将设置为范围界限.否则,它将在绑定的范围上查找名称为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

原文链接:https://www.f2er.com/angularjs/140778.html

猜你在找的Angularjs相关文章