karma-webpack无法运行测试

时间:2019-01-23 16:27:33

标签: angularjs unit-testing webpack karma-runner karma-webpack

编辑:从another answer起,我决定尝试从karma-webpack 3.0.5升级到4.0.0-rc.2,然后开始出现实际错误。它开始抱怨没有定义angular,然后我意识到我是从home.spec.js文件中导入tests.bundle.spec文件,而不是依赖上下文来导入它(在调试时就这样做了,却忘记了)。删除多余的导入后,我的测试成功运行!一旦SO允许我回答自己的问题,我将用一个答案更新这个问题。

我可以肯定的是,尽管似乎webpack会创建测试包,但karma甚至没有加载我的测试包文件。

我似乎看不到tests.bundle.spec.jshome.spec.js文件中的任何console.log。当我具有singleRun = false并刷新后检查了衍生的Chrome窗口中的控制台(测试应重新运行)时,我在“网络”标签中看到tests.bundle.spec.js文件已加载,但是什么也没看到在控制台中,并且在html文件中未引用。 html页面中加载的唯一脚本是socket.io.jskarma.js

edit:从Chrome打开“调试”页面后,我确实看到我的tests.bundle.spec.js捆绑包已加载,但是其中任何包含的模块都无法运行。我已经将断点放入测试脚本中,甚至将tests.bundle.spec.js代码(例如,在为require设置上下文时)中都放入了断点,但是没有一个断点被触发。我一定在某处缺少某些东西,因为Karma从未初始化任何这些模块。我什至在__webpack_require__函数中添加了断点,并且断点没有被触发。因此,不需要/导入我的任何模块。

Webpack肯定会构建该模块,我在yarn test命令(运行karma start的控制台输出中看到了这一点:

Entrypoint src/tests.bundle.spec = vendors~src/tests.bundle.spec.bundle.js src/tests.bundle.spec.js
[./ sync recursive home\.spec\.js$] . sync home\.spec\.js$ 192 bytes {src/tests.bundle.spec} [built]

这是我的结构/配置

结构:

-src
--app
---home
----home.js
----home.spec.js
--tests.bundle.spec.js
karma.conf.js
webpack.test.js

karma.conf.js

var webpackConfig = require('./webpack.test.js');

module.exports = function (config) {
    process.env.BABEL_ENV = 'karma';

    config.set({

        basePath: '',
        frameworks: ['jasmine'],


        // list of files / patterns to load in the browser
        files: [
            {
                pattern: './src/tests.bundle.spec.js',
                watched: false
            }
        ],

        // plugins
        plugins: [
            'karma-webpack',
            'karma-jasmine',
            'karma-sourcemap-loader',
            'karma-chrome-launcher'
        ],

        preprocessors: {
            './src/tests.bundle.spec.js': ['webpack', 'sourcemap']
        },

        // Webpack config
        webpack: webpackConfig,
        webpackServer: {
            noInfo: false
        },

        reporters: ['progress'],

        // web server port
        port: 9876,

        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,

        browsers: [
            'Chrome'
        ],
        singleRun: false,
        concurrency: Infinity
    })
}

webpack.test.js

const webpack = require("webpack");
const path = require('path');

const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    devtool: 'eval-source-map',
    entry: {
        app: path.resolve(__dirname, './src/index.js')
    },
    output: {
        path: path.resolve(__dirname, './build_app/'),
        filename: 'app-[name].js',
        chunkFilename: 'app-vendors.[chunkhash].js'
    },
    module: {
        rules: [

            // JavaScript source files for the LeadingReach application
            {
                test: /\.js$/,
                exclude: /(node_modules)(\.spec\.js$)/,
                rules : [
                    {
                        loader: 'babel-loader'
                    },
                    {
                        loader: 'eslint-loader',
                        options: {
                            emitError: true,
                            emitWarning: true,
                            failOnError: true,
                            globals: [
                                '_',
                                'angular',
                                'lrenums',
                                'readJSON'
                            ]
                        }
                    }
                ]
            },

            // JavaScript test files
            {
                test: /\.spec.js$/,
                exclude: /(node_modules)/,
                use : [
                    'babel-loader'
                ]
            },

            // Templates (non-compiled)
            {
                test: /\.tpl.html$/,
                exclude: /\.tpl.html2js$/,
                loader: ['file-loader?name=[path][name].[ext]?[hash]', 'extract-loader', 'html-loader']
            },

            // LESS files
            {
                test: /\.less$/,
                use: ['style-loader', 'css-loader', 'less-loader']
            },

            // CSS files
            {
                test: /\.css$/,
                loader: ['style-loader', 'css-loader']
            },

            // Static files
            {
                test: /\.(jpe?g|gif|png|ico)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]?[hash]',
                        outputPath: 'assets/images/'
                    }
                }]
            },

            // Font files
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]?[hash]',
                        outputPath: 'fonts/'
                    }
                }]
            }
        ]
    },
    optimization: {
        namedChunks: true,
        splitChunks: {
            chunks: "all",
            minSize: 0,
            cacheGroups: {
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    priority: -10,
                    chunks: 'all',
                    minSize: 0
                }
            }
        }
    },
    plugins: [
        // Clean build_app folder
        new CleanWebpackPlugin(['build_app'], {
            // Write logs to console.
            verbose: true,

            // perform clean just before files are emitted to the output dir
            // Default: false
            beforeEmit: true
        }),

        // Create our index.php file
        new HtmlWebpackPlugin({
            template: './src/index.php',
            filename: 'index.php',
            inject: 'head'          // place scripts in head because we bootstrap the app at the end of the body
        }),

        // Expose _ (underscoreJS) to the global scope
        new webpack.ProvidePlugin({
            _: 'underscore'
        })
    ]
};

tests.bundle.spec.js

const context = require.context('./', true, /.+home\.spec\.js$/);

console.log('================WHEEEEEE==============');
console.log(context.keys());

/*
 * For each file, call the context function that will require the file and load it up here.
 */
context.keys().forEach(function(key) {
    context(key);
});

home.spec.js

// Import dependencies
console.log('============HELLOOOOOOO123123123123==============');
require('angular');
require('angular-mocks');
import './home.js';

console.log('============HELLOOOOOOO==============');
describe('home section', function () {
    console.log('============HELLOOOOOOO222222==============');

    it('should run test', inject(function () {
        expect(1).toEqual(1);
    });
}

运行测试时,我得到Executed 0 of 0 ERROR (0.001 secs / 0 secs)

4 个答案:

答案 0 :(得分:1)

对我来说,这是与optimization.splitChunks相关的问题。从karma-webpack-config中删除它后,我的测试被发现了。

答案 1 :(得分:1)

您需要输入karma.conf.js

callback: function(){window.__karma__.start()}

答案 2 :(得分:0)

最终解决了我自己的问题,对不起,因为自原始帖子以来更新答案的时间过长。

从另一个答案中,我决定尝试从karma-webpack 3.0.5升级到4.0.0-rc.2,然后开始出现实际错误。它开始抱怨没有定义角度,然后我意识到我是从tests.bundle.spec文件中导入home.spec.js文件,而不是依靠上下文来导入它(在调试时就这样做了,却忘记了它)。删除多余的导入后,我的测试成功运行了!

答案 3 :(得分:0)

在更新到Webpack 5时,我遇到了同样的问题。测试执行:0,共0。准备寻求支持时,我创建了一个仓库https://github.com/svenbluege/karma-with-webpack-5-test,并在此处找到了解决方案。

修复非常简单。您需要像这样禁用分块:

 webpack: {
  // webpack configuration => makes karma-webpack work!
  optimization: {
    runtimeChunk: false,
    splitChunks: false
  },
  module: {
    rules: [

默认情况下,karma-webpack启用了分块。感谢Johannes的提示(https://stackoverflow.com/a/55576353/1680552)!