Karma + Webpack + Angularjs-所有测试均通过,但因果报错(退出代码为1)

时间:2019-05-14 18:20:30

标签: javascript angularjs webpack karma-jasmine

karma 4.0.1,webpack 4.31.0,angular 1.6.8,karm-jasmine 2.0.1,jasmine-core 3.4.0

在工作中,我刚将我们的angularjs应用程序从一个老式的gulp构建过程转换为webpack + es6。在此过程进行顺利的过程中,除非出现一些头痛和打ic的事情。到现在为止。

Karma成功运行了我的所有测试,所有测试都通过了,但是Karma退出并显示代码1,并且抛出没有文件名或行号的错误来进行调查。

我已经进行了2天的谷歌搜索,尝试了许多其他事情,但到目前为止都没有成功。任何帮助表示赞赏。

14 05 2019 13:27:49.456:INFO [karma-server]: Karma v4.0.1 server started at http://0.0.0.0:10002/
14 05 2019 13:27:49.457:INFO [launcher]: Launching browsers ChromeHeadless-C with concurrency unlimited
14 05 2019 13:27:49.528:INFO [launcher]: Starting browser ChromeHeadless
14 05 2019 13:27:50.081:INFO [HeadlessChrome 74.0.3729 (Mac OS X 10.14.4)]: Connected on socket U30VLDHr805gOx4vAAAA with id 50392440
HeadlessChrome 74.0.3729 (Mac OS X 10.14.4) ERROR
  {
    "message": "An error was thrown in afterAll\nSyntaxError: Unexpected string",
    "str": "An error was thrown in afterAll\nSyntaxError: Unexpected string"
  }
HeadlessChrome 74.0.3729 (Mac OS X 10.14.4): Executed 1964 of 1964 ERROR (11.787 secs / 0 secs)

npm debug.log

0 info it worked if it ends with ok
1 verbose cli [ '/Users/riegersn/.nvm/versions/node/v8.9.4/bin/node',
1 verbose cli   '/Users/riegersn/.nvm/versions/node/v8.9.4/bin/npm',
1 verbose cli   'run',
1 verbose cli   'test' ]
2 info using npm@6.5.0
3 info using node@v8.9.4
4 verbose run-script [ 'pretest', 'test', 'posttest' ]
5 info lifecycle vpower-ui@4.9.0~pretest: vpower-ui@4.9.0
6 info lifecycle vpower-ui@4.9.0~test: vpower-ui@4.9.0
7 verbose lifecycle vpower-ui@4.9.0~test: unsafe-perm in lifecycle true
8 verbose lifecycle vpower-ui@4.9.0~test: PATH: /Users/riegersn/.nvm/versions/node/v8.9.4/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/riegersn/vesi/vpower-ui/node_modules/.bin:/Users/riegersn/.nvm/versions/node/v8.9.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
9 verbose lifecycle vpower-ui@4.9.0~test: CWD: /Users/riegersn/vesi/vpower-ui
10 silly lifecycle vpower-ui@4.9.0~test: Args: [ '-c', 'karma start' ]
11 silly lifecycle vpower-ui@4.9.0~test: Returned: code: 1  signal: null
12 info lifecycle vpower-ui@4.9.0~test: Failed to exec test script
13 verbose stack Error: vpower-ui@4.9.0 test: `karma start`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/Users/riegersn/.nvm/versions/node/v8.9.4/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (/Users/riegersn/.nvm/versions/node/v8.9.4/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:925:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid vpower-ui@4.9.0
15 verbose cwd /Users/riegersn/vesi/vpower-ui
16 verbose Darwin 18.5.0
17 verbose argv "/Users/riegersn/.nvm/versions/node/v8.9.4/bin/node" "/Users/riegersn/.nvm/versions/node/v8.9.4/bin/npm" "run" "test"
18 verbose node v8.9.4
19 verbose npm  v6.5.0
20 error code ELIFECYCLE
21 error errno 1
22 error vpower-ui@4.9.0 test: `karma start`
22 error Exit status 1
23 error Failed at the vpower-ui@4.9.0 test script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

karma.conf.js

var webpackConfig = require('./webpack.config.js')({ development: true });

module.exports = function (config) {
    config.set({
        basePath: './',

        frameworks: ['jasmine'],

        files: [
            './app/init.js',
            './node_modules/angular-mocks/angular-mocks.js',
            './test/lib/**/*.js',
            './test/mock/**/*.js',
            './app/**/*.mock.js',
            './app/**/*.spec.js'
        ],

        webpack: webpackConfig,

        reporters: ['progress'],

        preprocessors: {
            './app/init.js': 'webpack'
        },

        port: 9999,

        browserNoActivityTimeout: 60000,

        logLevel: config.LOG_INFO,

        autoWatch: false,

        singleRun: true,

        browsers: ['ChromeHeadless-C'],

        customLaunchers: {
            'ChromeHeadless-C': {
                base: 'ChromeHeadless',
                flags: ['--disable-web-security']
            },
            'Chrome-C': {
                base: 'Chrome',
                flags: ['--disable-translate', '--disable-extensions', '--disable-web-security']
            }
        },

        plugins: [
            'karma-jasmine',
            'karma-webpack',
            'karma-chrome-launcher',
            // 'karma-sourcemap-loader'
        ],
        client: {
            jasmine: {
                random: false
            }
        }
    });
};

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const vpowerHost = require('./tools/vpowerHost');
const CopyPlugin = require('copy-webpack-plugin');
const Autoprefixer = require('autoprefixer');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const log = function() {
    console.log('webpack-config ::', ...arguments);
};

module.exports = env => {
    const HOST = vpowerHost(process.env.NODE_ENV);
    log('host ->', HOST);
    log('build mode ->', env.production ? 'production' : 'development');

    let config = {
        context: path.resolve(__dirname, 'app'),
        entry: './init.js',
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: '[name].js'
        },
        resolve: {
            alias: {
                '@Products': path.resolve(__dirname, 'app/products/'),
                '@Components': path.resolve(__dirname, 'app/shared/components/'),
                '@Controllers': path.resolve(__dirname, 'app/shared/controllers/'),
                '@Direcctives': path.resolve(__dirname, 'app/shared/directives/'),
                '@Filters': path.resolve(__dirname, 'app/shared/filters/'),
                '@Modals': path.resolve(__dirname, 'app/shared/modals/'),
                '@Models': path.resolve(__dirname, 'app/shared/models/'),
                '@Services': path.resolve(__dirname, 'app/shared/services/'),
                '@Views': path.resolve(__dirname, 'app/shared/views/')
            }
        },
        module: {
            rules: [
                {
                    test: require.resolve('jquery'),
                    loader: 'expose-loader?jQuery!expose-loader?$'
                },
                {
                    test: require.resolve('moment'),
                    loader: 'expose-loader?moment'
                },
                {
                    test: /\.js$/,
                    loader: 'babel-loader',
                    include: path.resolve(__dirname, 'app'),
                    exclude: /node_modules/,
                    options: {
                        presets: ['@babel/preset-env']
                    }
                },
                {
                    test: /\.html$/,
                    loader: 'html-loader',
                    include: path.resolve(__dirname, 'app'),
                    options: {
                        root: path.resolve(__dirname, 'assets'),
                        attrs: ['img:src'],
                        minimize: env.production,
                        removeComments: env.production,
                        collapseWhitespace: env.production
                    }
                },
                {
                    test: /\.css$/,
                    use: [env.production ? MiniCssExtractPlugin.loader : 'style-loader', 'css-loader']
                },
                {
                    test: /\.scss$/,
                    use: [
                        env.production ? MiniCssExtractPlugin.loader : 'style-loader',
                        'css-loader',
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins: () => [Autoprefixer()]
                            }
                        },
                        'sass-loader'
                    ]
                },
                {
                    test: /\.(png|jpe?g|svg)$/,
                    loader: 'file-loader',
                    options: {
                        limit: 8000,
                        name: 'images/[name].[ext]'
                    }
                },
                {
                    test: /\.(jpg|png|gif|svg)$/,
                    loader: 'image-webpack-loader',
                    enforce: 'pre'
                },
                {
                    test: /\.(woff|woff2|eot|ttf)$/,
                    loader: 'file-loader?limit=100000',
                    options: {
                        name: 'fonts/[name].[ext]'
                    }
                }
            ]
        },
        plugins: [
            new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
            new CopyPlugin([
                {
                    from: __dirname + '/assets/json',
                    to: __dirname + '/dist/json'
                },
                {
                    from: __dirname + '/node_modules/amcharts-src/amcharts/plugins/export/libs',
                    to: __dirname + '/dist/amcharts/libs'
                },
                {
                    from: __dirname + '/node_modules/amcharts-src/amcharts/images',
                    to: __dirname + '/dist/amcharts/images'
                }
            ]),
            new MiniCssExtractPlugin({
                filename: '[name].css',
                chunkFilename: '[id].css'
            }),
            new HtmlWebpackPlugin({
                template: 'index.html',
                favicon: '../assets/images/favicon.ico',
                inject: true
            })
        ],
        devServer: {
            host: 'localhost',
            port: 9000,
            hot: true,
            proxy: {
                '/isoneplc': 'http://localhost:9001',
                '/csv-convert': 'http://localhost:9001'
            },
            allowedHosts: [
                '#####.localhost',
                '#####.localhost',
                '#####.localhost',
                '#####.localhost',
                '#####.localhost',
                '#####.localhost',
                '#####.localhost'
            ]
        }
    };

    config.mode = env.production ? 'production' : 'development';

    if (env.production) {
        log('adding source maps');
        log('adding optimizations');
        config.devtool = 'source-map';
        config.optimization = {
            minimizer: [
                new UglifyJsPlugin({
                    parallel: true
                }),
                new OptimizeCSSAssetsPlugin({
                    cssProcessorPluginOptions: {
                        preset: ['default', { discardComments: { removeAll: true } }]
                    }
                })
            ],
            splitChunks: {
                chunks: 'all'
            }
        };
        config.plugins.push(new BundleAnalyzerPlugin());
    } else if (env.production && HOST === '##########.com') {
        config.devtool = 'source-map';
        log('adding source maps');
    }

    return config;
};

1 个答案:

答案 0 :(得分:0)

在对karms-jasmine@2.0.1包进行了一些调试之后,在lib / adapter.js:170中,我能够在处理结果对象之前将其打印出来。该对象包含错误的文件名和行号,即运行测试时未提供的信息。

罪魁祸首是一个未由​​webpack处理的es6 js文件,浏览器遇到了一些es6代码,并且不知道如何处理它。该文件实际上是不需要的,因此一旦删除它,此问题就解决了。