Angular.js使用html2js将指令与外部模板联合起来 - 无法加载模板

 fangsi155_7827d9 发布于 2023-02-04 12:55

我正在尝试测试使用外部模板的指令.我没有运气,尝试了以下所有解决方案:

NG-指令测试

如何测试使用templateUrl和控制器的指令?

AngularJS + Karma + Ng-html2js =>无法实例化模块... html

我创建了一个测试指令(一个简单的div)并使用内联"模板"和外部"templateUrl"对其进行了测试.内联解决方案有效,而外部解决方案不:

   angular.module('AdUnit').directive('actionButton',function($location){
        return{
            scope:{
                actionName: '@'
            },
            restrict: 'E',
            //template: "
action button
", templateUrl: '/staticfiles/adunit/html/directives/actionButtonTemplate.html', controller: ['$scope', function($scope){ $scope.click = function(){ $scope.$emit('ACTION_CLICK', $scope.actionName); } }] } }); describe("Unit: Testing action button directive", function() { var elm, scope, linkFn; beforeEach( module('AdUnit') ); beforeEach(module('/staticfiles/adunit/html/directives/actionButtonTemplate.html')); beforeEach(inject(function($rootScope, $compile) { elm = angular.element(''); scope = $rootScope; linkFn = $compile(elm); linkFn(scope); scope.$digest(); // have to digest to bring html from templateCache console.log('post compile',elm.html());// <== the html here still have {{}} })); it('should show a thumb',function() { console.log('post link',elm.html());// <== the html is bound expect(elm.text()).toBe("action button"); }); });

我的Karma配置文件:

  module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '',


    // frameworks to use
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
        'http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js',
        'http://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js',
        'http://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.js',
        'http://code.angularjs.org/1.0.6/angular-mocks.js',
        '../html/*.html',
        '../html/directives/*.html',
        '../js/adUnit.js',
        '../js/controllers/*.js',
        '../js/directives/*.js',
        '../js/services/*.js',
        '../*.js',
         '../**.*.js',
         '**/*.tests.js'
    ],

    preprocessors : {
        '../html/**/*.html': ['ng-html2js']
    },

     /* ngHtml2JsPreprocessor: {
          'AdUnit': '/staticfiles/adunit/html/directives/actionButtonTemplate.html'
          *//*moduleName: '/staticfiles/adunit/html/directives/internalPlayerTemplate.html'*//*
      },*/

    // list of files to exclude
    exclude: [

    ],


    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['Chrome'],


    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,


    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};

我一直收到以下错误:

Failed to instantiate module /staticfiles/adunit/html/directives/actionButtonTemplate.html due to:
Error: [$injector:nomod]

任何帮助将不胜感激!

编辑:@MK萨菲的答案解决了我的问题.我错过了以下内容:

 ngHtml2JsPreprocessor: {
     'moduleName': 'Templates',

     // Function that transforms the path to look exactly like
     // you have it in templateUrl in your Angular code
     //
     // Mine looks like this
     cacheIdFromPath: function(filepath) {
         return filepath.match(/\/staticfiles\/adunit\/html\/directives\/.*\.html/);
     }
  },

在每次测试之前:

 beforeEach(module('Templates'));

正则表达式指向与指令的"templateUrl"相同的路径很重要,因为html2js将使用此路径缓存这些模板(有关详细信息,请参阅html2js)

1 个回答
  • 我在测试中正确设置了这个设置,并且您的设置看起来正确,除了一些事情.

    对您的Karma配置文件进行以下更改:

    ngHtml2JsPreprocessor = {
      'moduleName': 'Templates',
    
      // Function that transforms the path to look exactly like 
      // you have it in templateUrl in your Angular code
      //
      // Mine looks like this
      cacheIdFromPath: function(filepath) {
        return filepath.match(/views\/.*/)[0]
      }
    }
    

    然后在您的测试中beforeEach包括Templates您在上面的Karma配置中指定的模块:module('Templates')

    beforeEach(function() {
      module('Templates')
    })
    

    2023-02-04 12:57 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有