angularjs – 如何单元测试指令中的隔离范围
发布时间:2020-12-17 09:15:31 所属栏目:安全 来源:网络整理
导读:我试图单元测试一个简单的指令,但范围中的变量总是未定义的. 指令Src代码: .directive('ratingButton',['$rootScope',function($rootScope) { return { restrict: "E",replace: true,template: 'button type="button" class="btn btn-circle" ng-class="get
我试图单元测试一个简单的指令,但范围中的变量总是未定义的.
指令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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- /etc/profile,/etc/bashrc,~/.bash_profile,~/.bashrc
- 设置-eu时,bash未绑定变量不会导致从子shell退出
- fedora 23 lvm2格式 根目录磁盘空间不足 扩容方法
- twitter-bootstrap – Bootstrap 3 Navbar不会在移动浏览器
- 在Angular2中处理错误的最佳实践
- angularjs – 使用量角器测试websockets服务器
- angularjs – 如何在Angular 1.5组件中对具有不同名称的绑定
- AngularJs bootstrap详解及示例代码
- angularjs离子和全局变量:使变量在全球范围内可用的最佳实
- bootStrap实现tab页切换