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

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

指令Src代码

  1. .directive('ratingButton',['$rootScope',function($rootScope) {
  2. return {
  3. restrict: "E",replace: true,template: '<button type="button" class="btn btn-circle" ng-class="getRatingClass()"></button>',scope: {
  4. buttonRating: "="
  5. },link: function(scope,elem,attr) {
  6. scope.getRatingClass = function() {
  7. if (!scope.buttonRating)
  8. return '';
  9. else if (scope.buttonRating.toUpperCase() === 'GREEN')
  10. return 'btn-success';
  11. else if (scope.buttonRating.toUpperCase() === 'YELLOW')
  12. return 'btn-warning warning-text';
  13. else if (scope.buttonRating.toUpperCase() === 'RED')
  14. return 'btn-danger';
  15. else if (scope.buttonRating.toUpperCase() === 'BLUE')
  16. return 'btn-info';
  17. }
  18. }
  19. };
  20. }])

测试:

  1. describe('Form Directive: ratingButton',function() {
  2.  
  3. // load the controller's module
  4. beforeEach(module('dashboardApp'));
  5.  
  6. var scope,element;
  7.  
  8. // Initialize the controller and a mock scope
  9. beforeEach(inject(function($compile,$rootScope) {
  10. scope = $rootScope.$new();
  11.  
  12. //set our view html.
  13. element = angular.element('<rating-button button-rating="green"></rating-button>');
  14. $compile(element)(scope);
  15. scope.$digest();
  16. }));
  17.  
  18. it('should return appropriate class based on rating',function() {
  19. //console.log(element.isolateScope());
  20. expect(element.isolateScope().buttonRating).toBe('green');
  21. expect(element.isolateScope().getRatingClass()).toBe('btn-success');
  22.  
  23. });
  24.  
  25. });

我在另一个指令单元测试中使用了类似的代码,通过元素属性传递值,并且按预期工作.对于这个测试buttonRating总是不确定不知道从哪里去(我是相当新的茉莉/羯磨)

任何帮助将是伟大的!

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

即scope.buttonRating =’green’;

angular.element(‘< rating-button button-rating =“buttonRating”>< / rating-button>‘)

尝试:

  1. // Initialize the controller and a mock scope
  2. beforeEach(inject(function($compile,$rootScope) {
  3. scope = $rootScope.$new();
  4. scope.buttonRating = 'green'; //<-- Here
  5. //set our view html.
  6. element = angular.element('<rating-button button-rating="buttonRating"></rating-button>');
  7. $compile(element)(scope);
  8. scope.$digest();
  9. }));
  10.  
  11. it('should return appropriate class based on rating',function() {
  12. expect(element.isolateScope().buttonRating).toBe('green');
  13. expect(element.isolateScope().getRatingClass()).toBe('btn-success');
  14.  
  15. });

Plnkr

猜你在找的Angularjs相关文章