Page 288 - AngularJS权威教程
P. 288

268  第 19 章  测试


                 $templateCache服务允许$http服务缓存经过XHR的模板请求,这样它们就只会被请求一
             次。当一个模板被取到了,它的内容就会存储在$templateCache中,用模板路径作键。例如,
             当获取下面的实例指令时,它会请求templateUrl并且把模板的内容放在$templateCache中:

                 angular.module('myApp')
                     .directive('notification', function($timeout) {
                         return {
                             restrict: 'A',
                             scope: { ngModel: '=' },
                             templateUrl: 'views/templates/notification.html',
                 }});
                 $templateCache 会把这个模板的 内容保持 在 $templateCache('views/templates/
             notification.html')中。如果已经预先在$templateCache中存放了测试所需的指令文件内容,
             就可以使用$templateCache来阻止在指令的单元测试中再产生请求。
                 可以使用优秀的karma-ng-html2js-preprocessor包来把模板转换成可在测试中使用的
             Angular模块。

                 karma-ng-html2js-preprocessor
                 首先,需要安装包:

                 $ npm install --save-dev karma-ng-html2js-preprocessor
                 做好之后,需要修改karma.conf.js来使用html2js预处理器。我们需要在preprocessors
             数组中添加html2js预处理器:

                 preprocessors: {
                     'app/views/**/*.html': ['ng-html2js']
                 },
                 // ...
                 为了让所有模板都被karma加载,需要设置files数组来加载模板。例如,如果模板放在
             app/view/下面,可以把这段加到files数组中以加载它们(根据具体项目来修改这个路径):

                 files: [
                     'app/bower_components/angular/angular.js',
                     // ...
                     'app/views/**/*.html',
                     'app/scripts/*.js',
                     // ...
                 ]
                 围绕预处理器,需要加一些配置。我们会要创建用于注入到测试中的模块。此外,也会要把
             模板的cacheId设置为模板路由的真实文件路径。ng-html2js包允许我们为每个模板定义它,它
             存放在files数组中。

                 如果我们从指令中获取模板,很可能不是指向app/路径的(可以是相对于app/目录的)。在这
             些情况下,我们会从这个路径剥离路径,这样就可以引用这个URL,因为它已经被指令自己请求
             过了。配置可能看上去像下面这样:

                 // ...
                 ngHtml2JsPreprocessor: {
                     moduleName: 'templates',
   283   284   285   286   287   288   289   290   291   292   293