2

在安装 .NET Core 2.0 SDK 后,我使用 Visual Studio 2017 Update 3 中的 Angular ASP.NET Core 2.0 模板启动了一个项目。

Karma 中的测试工作正常,但我想向 Karma 添加代码覆盖率。我尝试了几种不同的解决方案,但似乎没有什么能完全奏效。我想出的最好的方法是涵盖了从测试中引用的类(但不是 ClientApp 中的所有打字稿类),但是生成的报告中的突出显示已关闭,并且消息没有意义。

这就是我所做的:

包.json

"devDependencies": {
    "@types/chai": "4.0.1",
    "@types/jasmine": "2.5.53",
    "chai": "4.0.2",
    "istanbul-instrumenter-loader": "^3.0.0",
    "jasmine-core": "2.6.4",
    "karma": "https://registry.npmjs.org/karma/-/karma-1.7.0.tgz",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-coverage": "^1.1.1",
    "karma-jasmine": "1.1.0",
    "karma-remap-istanbul": "https://registry.npmjs.org/karma-remap-istanbul/-/karma-remap-istanbul-0.6.0.tgz",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "2.0.3"
  }

Karma.conf.js:

module.exports = function (config) {
    var webpackConfig = require('../../webpack.config.js')().filter(config => config.target !== 'node');
    webpackConfig[0].devtool = 'inline-source-map';

    config.set({
        basePath: '.',
        frameworks: ['jasmine'],
        files: [
            '../../wwwroot/dist/vendor.js',
            './boot-tests.ts'
        ],
        preprocessors: {
            './boot-tests.ts': ['webpack', 'sourcemap']
        },
        reporters: ['progress', 'coverage', 'karma-remap-istanbul'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome'],
        mime: { 'application/javascript': ['ts','tsx'] },
        singleRun: false,
        webpack: webpackConfig, // Test against client bundle, because tests run in a browser
        webpackMiddleware: { stats: 'errors-only' },
        remapIstanbulReporter: {
            reports: {
                html: 'coverage'
            }
        }
    });
};

webpack.config.js:

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);

    const tsUse = isDevBuild ? [
        {
            loader: 'istanbul-instrumenter-loader',
            options: {
                esModules: true
            }
        },
        'awesome-typescript-loader?silent=true',
        'angular2-template-loader'
    ] : '@ngtools/webpack';

    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: ['.js', '.ts'] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                {
                    test: /\.ts$/, include: /ClientApp/,
                    use: tsUse
                },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                {
                    test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize']
                },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AotPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};
4

1 回答 1

3

我最近一直在研究这个问题,经过一番挖掘,我最终得到了以下解决方案。

注意:请参阅这篇文章底部的参考资料,了解我最终找到的解决方案。这已经(必然)与来源不同了,所以我认为我不应该在版权方面遇到麻烦。

首先,我将这些添加到我的解决方案的package.json中,该解决方案是使用 Visual Studio 2017(我认为是 15.3 及更高版本)提供的新 ASP.NET Core 2.0 Angular 模板开始的。将这些添加到package.jsondevDependencies的部分。

"karma-sourcemap-loader": "^0.3.7",
"karma-remap-istanbul": "^0.6.0",
"istanbul-instrumenter-loader": "^3.0.0"

运行npm install以将这些位添加到应用程序中,或者保存package.json并让 VS 完成它。

接下来,我更改了ClientApp/test/boot-tests.ts文件。

更改此行:

const context = require.context('../app/', true, /\.spec\.ts$/);

对此:

const context = require.context('../app', true, /\.ts$/);

这(上)直接来自下面的第一个参考。

接下来,我将ClientApp/test/karma.conf.js内容替换为:

const path = require('path');

var webpackConfig = require('../../webpack.config.js')().filter(config => config.target !== 'node')[0];
webpackConfig.module.rules.push({
    test: /\.ts$/,
    include: [path.resolve(__dirname, '../app')],
    use: {
        loader: 'istanbul-instrumenter-loader?force-sourcemap=true',
        options: { esModules: true }
    },
    enforce: 'post',
    exclude: [/\.spec\.ts$/]
});

module.exports = function (config) {
    config.set({
        basePath: '.',
        frameworks: ['jasmine'],
        files: ['../../wwwroot/dist/vendor.js', './boot-tests.ts'],
        preprocessors: {
            './boot-tests.ts': ['webpack']
        },
        reporters: ['progress', 'karma-remap-istanbul'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome'],
        mime: { 'application/javascript': ['ts', 'tsx'] },
        singleRun: true,
        webpack: webpackConfig,
        webpackMiddleware: { stats: 'errors-only' },
        remapIstanbulReporter: {
            reports: {
                html: 'ClientApp/test/coverage',
                'text-summary': null
            }
        }
    });
};

现在,当我npm test从应用程序的根目录运行时,我会在ClientApp/test/coverage文件夹中生成覆盖率报告(在您选择的浏览器中打开index.html)。我还在karma.conf.jstext-summary中添加了报告选项,因此您也可以在命令行上获得摘要。

如果您希望在更新代码和单元测试时运行和刷新,可以将karma.conf.jssingleRun中的更改为 false。当我在迁移到 Angular 5.0.0 后使用模板尝试所有这些时,我遇到了一个问题。使用 ng 5.0.0,会输出编译时警告,这会导致 karma 一遍又一遍地重新编译,无论代码是否有更改。ng 4.2.5 没有这个问题,这是 Core 2.0 模板使用的开箱即用的版本。

QIQO.Core.Ng.Coverage是我有一个项目的地方,我添加了这些更改供您查看,如果您愿意的话。

参考:

JavaScriptServices wiki 中的Angular2SpaCodeCoverage 。

这将使您大部分时间到达那里,但是对karma.conf.js进行更改的部分不太正确,并且不适用于最新版本的模板或 webpack(我使用的是 3.8. 1 在我写这篇文章的时候)。它对sourcemap-istanbul-instrumenter-loader包的使用似乎也不再起作用了。这将我引向下一个参考。

问题:Angular 2 和 webpack 2 的代码覆盖率

正是这个问题线程中最后 2 篇文章中的信息帮助我完成了这篇文章。感谢Tdortiz!添加options: { esModules: true }karma.conf.js,并使用istanbul-instrumenter-loader而不是sourcemap-istanbul-instrumenter-loader技巧。

于 2017-11-12T15:46:14.747 回答