[英]Unit testing AngularJS directives
我如何對我的指令進行單元測試?
我擁有的是什么
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);
});
});
這不起作用,因為該指令在app模塊上注冊,我不想包含該模塊,因為這將使我的所有config
和run
代碼運行。 這將破壞將指令作為一個單獨的單元進行測試的目的。
我是否應該將所有指令放在一個單獨的模塊中並加載它? 還是有其他聰明的方法來解決這個問題嗎?
編輯:自從我上次回答以來,我發現問題已經改變了。
您需要將您的指令放在一個獨立的模塊中。
例如:
angular.module('MyModule.directives');
要僅測試該模塊,您可以在測試中顯式加載該模塊,如下所示:
beforeEach(module('MyModule.directives'));
這將加載該模塊及其所有依賴項。
請記住在應用程序的MyModule定義中將指令模塊聲明為依賴:
angular.module('MyModule', ['MyModule.directives', ...]);
您應該在'youapp.directives'模塊中聲明所有指令,並在指令測試中包含該模塊。
在你的app.js中
angular.module('myApp', ['myApp.controllers', 'myApp.directives', 'myApp.services', 'myApp.filters']).config(...)
在你的directives.js中
angular.module('myApp.directives', []) .directive(.....)
最后你的指令規范.js
describe('directives specs', function() {
beforeEach(module('myApp.directives'));
describe('range', function() {
...
});
});
angular-seed項目https://github.com/angular/angular-seed似乎認為指令應該放在他們自己的模塊中,然后是基礎應用程序模塊的依賴項。
因此指令進入名為“myApp.directives”的模塊:
angular.module('myApp.directives', []).
directive('appVersion', ['version', function(version) {
return function(scope, elm, attrs) {
elm.text(version);
};
}]);
然后基礎應用程序模塊將指令模塊添加為依賴性
// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: MyCtrl1});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: MyCtrl2});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
那么他們的測試示例只取決於指令模塊
describe('directives', function() {
beforeEach(module('myApp.directives'));
etc...
我還沒有用你或我的代碼嘗試這個,但看起來你主要是尋找最常見的練習指導。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.