我該如何測試我的指令?單元測試AngularJS指令
我有什麼是
angular.module('MyModule').
directive('range', function() {
return {
restrict: 'E',
replace: true,
scope: {
bindLow: '=',
bindHigh: '=',
min: '@',
max: '@'
},
template: '<div><select ng-options="n for n in [min, max] | range" ng-model="bindLow"></select><select ng-options="n for n in [min, max] | range" ng-model="bindHigh"></select></div>'
};
})
在我的單元測試我想從一個非常簡單的測試
describe('Range control', function() {
var elm, scope;
beforeEach(inject(function(_$compile_, _$rootScope) {
elm = angular.element('<range min="1" max="20" bind-low="low" bind-high="high"></range>');
var scope = _$rootScope_;
scope.low = 1;
scope.high = 20;
_$compile_(elm)(scope);
scope.$digest();
}));
it('should render two select elements', function() {
var selects = elm.find('select');
expect(selects.length).toBe(2);
});
});
這不工作,雖然作爲該指令被註冊的應用模塊並且我不想包含該模塊,因爲這會使我的所有代碼都運行config
和run
。這將把作爲單獨單位測試指令的目的打敗。
我應該把我所有的指令放在一個單獨的模塊中,並加載?或者有沒有其他解決這個問題的巧妙方法?
記:你beforeEach內再次定義變種範圍。另外:_ $ rootScope vs _ $ rootScope _ – felix 2013-06-05 09:58:23