角度分量的绝对或相对“templateUrls”

时间:2017-11-27 18:17:25

标签: angular webpack karma-runner

有人可以帮我解决1 vs 2的这种情况吗?

1)Angular项目在生产中作为AoT。这需要将我的源代码更改为具有相对的templateUrl和styleUrls到component.ts文件。

2)角度业力为单位测试的JiT。这需要将我的源代码更改为具有绝对的templateUrl和styleUrls,否则单元测试将抛出404以查找.html文件。

我想避免在源代码中维护相对AND和绝对路径。

我有什么选择?什么是最佳做法?

(我正在使用带有aot和Karma的WEBPACK,而不是angular-cli)

谢谢!

更新: 我们也将探索转换为angular-cli,但这是一个巨大的项目,如果有人知道angular-cli用来解决这个问题的技巧,这对我们来说是一个阻碍。甚至是解决方案,这样我们就可以恢复单元测试了!

我需要知道使用AoT或至少ALONG SIDE AoT运行单元测试的技巧(换句话说,使用一组templateUrls运行生产和jit单元测试)

再次感谢!

PS .. 这完全没有AoT(使用绝对URL),但是切换到AoT(使用相对于组件文件的URL)阻止了我们。

更新2 :(包括我所有的配置文件) 如果我必须创建另一个配置文件来运行测试(这是有意义的)但我想知道测试配置需要什么'魔术'才能运行JiT组件,现在我的网址都是相对的。

webpack.config.js

let webpack = require('webpack');
let path = require('path');
let aot = require('@ngtools/webpack');

module.exports = {
    entry: {
        main: './Angular/main'
    },
    output: {
        path: __dirname,
        filename: './dist/smartcommand-[name].min.js',
        // Lazy load modules by route & chunk
        chunkFilename: './dist/smartcommand-[name].chunk.[hash].min.js'
    },
    resolve: {
        extensions: ['.ts', '.js'],
        modules: [
            path.resolve('./'),
            path.resolve('./node_modules')
        ],
        alias: {
            'ng2-charts/charts/charts': 'node_modules/ng2-charts/bundles/ng2-charts.umd.min.js'
            //'ng2-dragula': 'node_modules/ng2-dragula/bundles/ng2-dragula.umd.min.js'
        }
    },
    module: {
        rules: [
            // Ahead of Time Compilation
            { test: /\.ts$/, loader: '@ngtools/webpack', exclude: [/\.(spec)\.ts$/] },
            // AoT requires all files to be loaded
            { test: /\.html$/, loader: 'html-loader' },
            { test: /\.css$/, loader: 'raw-loader' },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader', options: { name: '[path][name].[ext]' }
            }
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({ name: 'main' }),
        // Ahead of Time Plugin
        new aot.AngularCompilerPlugin({
            tsConfigPath: path.resolve('./Angular/tsconfig.json'),
            entryModule: path.resolve('./Angular/_app.module#SmartCommandModule')
            // Use this setting to turn off AoT
            //,skipCodeGeneration: true
        }),
        // Only load the necessary locales for moment
        new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en|es/)
    ],
    // Minimize webpack console output
    stats: { assets: false, children: false }
};

karma.config.js

/* Karma Configuration */
'use strict';
module.exports = function (config) {
    let appBase = 'Angular/'; // transpiled app JS and map files

    config.set({
        plugins: [
            'karma-jasmine',
            'karma-jasmine-html-reporter',
            //'karma-chrome-launcher',
            'karma-firefox-launcher',

            // preprocessors
            'karma-webpack',
            'karma-sourcemap-loader', // show proper (un-bundled) stack traces
            'karma-coverage', // capture unit test code coverage
            'karma-trx-reporter' // report coverage in VSTS
        ],

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        //browsers: ['Chrome'],
        browsers: ['Firefox'],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'karma-test-shim.js': ['webpack', 'coverage']
            // for debugging the tests
            //'karma-test-shim.js': ['webpack', 'sourcemap']
        },

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // list of files / patterns to load in the browser
        files: [
            // polyfills
            'node_modules/core-js/client/shim.js',

            'Scripts/jquery-3.1.1.min.js',
            'Scripts/jquery-ui-1.12.1.min.js',

            'node_modules/moment/moment.js',
            'node_modules/leaflet/dist/leaflet.js',
            'node_modules/nipplejs/dist/nipplejs.js',

            'node_modules/zone.js/dist/zone.js',
            'node_modules/zone.js/dist/long-stack-trace-zone.js',
            'node_modules/zone.js/dist/proxy.js',
            'node_modules/zone.js/dist/sync-test.js',
            'node_modules/zone.js/dist/jasmine-patch.js',
            'node_modules/zone.js/dist/async-test.js',
            'node_modules/zone.js/dist/fake-async-test.js',

            // rxJS
            { pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
            { pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },

            // other dependencies
            { pattern: 'node_modules/applicationinsights-js/**/*.js', included: false, watched: false },
            { pattern: 'node_modules/applicationinsights-js/**/*.js.map', included: false, watched: false },

            { pattern: 'node_modules/ng2-charts/**/*.js', included: false, watched: false },
            { pattern: 'node_modules/ng2-charts/**/*.js.map', included: false, watched: false },
            'node_modules/chart.js/dist/Chart.bundle.js',

            { pattern: 'node_modules/primeng/**/*.js', included: false, watched: false },
            { pattern: 'node_modules/ngx-slick/**/*.js', included: false, watched: false },

            { pattern: 'node_modules/ng2-dragula/**/*.js', included: false, watched: false },
            { pattern: 'node_modules/ng2-dragula/**/*.js.map', included: false, watched: false },

            // our SmartCommand bundle
            'dist/smartcommand-main.min.js',

            // our Karma tests
            { pattern: 'karma-test-shim.js', included: true, watched: true },

            // paths for debugging with source maps in dev tools
            { pattern: appBase + '**/*.ts', included: false, watched: false },
            { pattern: appBase + '**/*.js.map', included: false, watched: false },

            // our assets (HTML & CSS) paths loaded via Angular's component compiler
            { pattern: appBase + '**/*.html', included: false, watched: true },
            { pattern: appBase + '**/*.css', included: false, watched: true },
            { pattern: 'Content/*.css', included: true, watched: false },
            { pattern: 'Content/*.css.map', included: false, watched: false },
            { pattern: 'Content/Images/**/*', included: false, watched: false },
            { pattern: 'Content/images/**/*', included: false, watched: false }
        ],

        // proxied base paths for loading assets
        proxies: {
            // required for component assets fetched by Angular's compiler
            '/Angular/': '/base/Angular/',
            '/Content/': '/base/Content/'
        },

        // test results reporter to use
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'kjhtml', 'coverage', 'trx'],

        // karma code coverage
        coverageReporter: {
            // specify a common output directory 
            dir: 'coverage',
            reporters: [
                // reporters not supporting the `file` property 
                { type: 'html', subdir: 'report-html' },
                { type: 'lcov', subdir: 'report-lcov' },
                // reporters supporting the `file` property, use `subdir` to directly 
                // output them in the `dir` directory 
                { type: 'cobertura', subdir: '.', file: 'cobertura.txt' },
                { type: 'lcovonly', subdir: '.', file: 'report-lcovonly.txt' },
                { type: 'teamcity', subdir: '.', file: 'teamcity.txt' },
                { type: 'text', subdir: '.', file: 'text.txt' },
                { type: 'text-summary', subdir: '.', file: 'text-summary.txt' }
            ]
        },

        // get code coverage in VSTS
        trxReporter: { outputFile: 'test-results.trx', shortTestName: false },

        // 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,

        // continuous integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // concurrency level
        // how many browsers should be started simultaneous
        concurrency: Infinity,

        client: {
            captureConsole: false, // set to true if you need console output
            builtPaths: [appBase], // add more spec base paths as needed
            clearContext: false // leave Jasmine Spec Runner output visible in browser
        },

        // workaround for disconnects
        browserDisconnectTolerance: 5,
        browserNoActivityTimeout: 50000
    });
};

业力测试垫片

// 'No stack trace' is usually best for app testing.
Error.stackTraceLimit = 0;
// Uncomment to get full stacktrace output. Sometimes helpful, usually not.
//Error.stackTraceLimit = Infinity;

// Import all .spec.js files in our Angular folder
let appContext = require.context('./Angular', true, /\.spec\.js$/);
appContext.keys().forEach(appContext);

// Start the Test Environment
let testing = require('@angular/core/testing');
let browser = require('@angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());

1 个答案:

答案 0 :(得分:1)

这是我看到的问题。实际上,您正在使用两种不同的Webpack配置。显然,您的webpack.config.js是为AoT设置的。

但是,当您运行Karma时,您正在使用另一个不同的配置。 karma-webpack插件提供在Karma进程中运行的Webpack实例及其自己的配置。除非您自己在karma.config.js中编写代码以阅读webpack.config.js,否则Karma将完全忽略该文件。如此有效,当您运行Karma时,您运行的是不同的Webpack配置。问题是目前你的配置是空的,这意味着Angular正在处理templateUrlstyleUrls" raw",你得到了你得到的结果。

您需要使用加载程序设置Webpack,该加载程序将处理templateUrlstylesUrls以使Webpack处理它们。我会用angular2-template-loader来做这件事。

看看你的配置,似乎当Karma看到你的文件时,它们都被转换成了JavaScript。通常,angular2-template-loader用于TypeScript文件,但由于它使用正则表达式完成其工作,因此它也适用于JavaScript文件。

我希望将angular2-template-loader添加到karma.config.js的Webpack配置应该正常工作,并根据项目的具体需求进行调整:

webpack: {
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['angular2-template-loader'],
        // exclude: [...] You may want to exclude your test files here
        // to save some build time.
      },
      // etc. with raw-loader, html-loader and file-loader as needed.              
    ]},  
  }