12
我想单元测试一个简单的指令,但范围中的变量始终未定义。我如何单元测试隔离示波器指令
指令的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相当新)
任何帮助将是伟大的!
啊看起来像这样的工作。不知道为什么我没有想到这一点! – atsituab
不用担心会发生.. :) – PSL
呃,浪费了这么多时间在这个。对@正常工作,但=没有意识到你不能把文字字符串放在那里(这是UNBINDABLE)。很高兴Angular 2摆脱了引擎盖下的双向绑定。 – FlavorScape