【问题标题】:Failed to instantiate module error while running angularjs unit tests using karma html2js preprocessor使用 karma html2js 预处理器运行 angularjs 单元测试时无法实例化模块错误
【发布时间】:2014-10-29 18:32:14
【问题描述】:

我正在尝试使用 karma 预处理器,以便在单元测试中加载模板。

我的 angularjs 指令单元测试在运行测试时抛出“无法实例化模块错误”。我在 karma.conf.js 中使用 karma html2js 预处理器来获取指令单元测试中的模板。

karma.conf.js

config.set({
        preprocessors: {
            'Components/navBar/Templates/navBar.htm': ['ng-html2js']
        },

    files: [
    'Scripts/angular-mocks.js',
    ...
    ...
    'Client/Components/navBar/Templates/navBar.htm'
    ],
    ngHtml2JsPreprocessor: {
        moduleName: 'templates'
    }

navBar_testcase.js

describe("navbartesting", 
function () {
    var template;

beforeEach(module('templates'));

beforeEach(function () {
    module("navBar");
    inject(function ($rootScope, $compile, $httpBackend, $injector, $localStorage, $state, $templateCache, userSession, appConfig) {

        http = $httpBackend;
        $httpBackend = $injector.get('$httpBackend');
        ...
        ....
    });
});
});

在运行上述单元测试时,会抛出错误“无法实例化模块“模板””。这可能是什么问题?我们是否有任何物理路径要定义为在 karma 配置文件中包含“模板”模块?

【问题讨论】:

    标签: javascript angularjs unit-testing karma-jasmine


    【解决方案1】:

    有了这个配置,就可以制作模板了。缺点是它只会创建 view.tpl.html 而不是 test.tpl.html

     config.set({
            autoWatch: true,
            basePath: '../',
            browsers: ['Chrome'],
            frameworks: ['jasmine', 'requirejs'],
    
            reporters: ['progress'],
    
            plugins: [
                'karma-chrome-launcher',
                'karma-phantomjs-launcher',
                'karma-jasmine',
                'karma-requirejs',
                'karma-ng-html2js-preprocessor-requirejs'
            ],
    
            files: [
                // App-specific Code
                {pattern: 'src/**/*.js', included: false},
    
                // 3rd party code
                {pattern: 'lib/**/*.js', included: false},
    
                //test files
                {pattern: 'test/unit/**/*.js', included: false},
    
                'test/test-main.js',
                '**/test.tpl.html',
                '**/view.tpl.html'
            ],
            ngHtml2JsPreprocessor: {
                enableRequireJs: true,
                moduleName: 'templates',
                cacheIdFromPath: function (filepath) {
                    console.log('path=' + filepath.replace(/^.*[\\\/]/, ''));
                    return filepath.replace(/^.*[\\\/]/, '');
                },
            },
    
            exclude: [
                'src/main.js'
            ],
            preprocessors: {
                '**/*.html': ['ng-html2js']
        }
    

    【讨论】:

    • 我可以通过在 grunt 任务运行器中使用 'ngtemplates' 任务来解决为单元测试用例生成模板的问题。
    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    相关资源
    最近更新 更多