Angularjs karma网页包未运行测试

Angularjs karma网页包未运行测试,angularjs,unit-testing,webpack,karma-runner,karma-webpack,Angularjs,Unit Testing,Webpack,Karma Runner,Karma Webpack,编辑:从年开始,我决定尝试从karma webpack 3.0.5升级到4.0.0-rc.2,我开始出现实际错误。它开始抱怨angular没有定义,然后我意识到我正在从tests.bundle.spec文件导入我的home.spec.js文件,而不是依赖上下文来导入它(在调试时这样做,但忘记了它)。删除额外导入后,我的测试将成功运行!我会用答案更新这个问题一次,这样我就可以回答我自己的问题了 我相当确定karma甚至没有加载我的测试包文件,尽管webpack似乎创建了包 我似乎看不到tests.

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

我相当确定karma甚至没有加载我的测试包文件,尽管webpack似乎创建了包

我似乎看不到
tests.bundle.spec.js
home.spec.js
文件中的任何console.log。当我设置singleRun=false,并在刷新后在生成的Chrome窗口中检查控制台(测试应该重新运行)时,我在网络选项卡中看到
tests.bundle.spec.js
文件已加载,但在控制台中看不到任何内容,在html文件中也没有引用它。html页面中加载的唯一脚本是
socket.io.js
karma.js

编辑:从Chrome打开调试页面后,我确实看到正在加载我的
tests.bundle.spec.js
bundle,但是所包含的模块都没有运行过。我已经在测试脚本中设置了断点,甚至在
tests.bundle.spec.js
代码中也设置了断点(例如,在为require设置上下文时),但是没有一个断点被触发。我一定是遗漏了什么,因为因果报应从来没有初始化过这些模块。我甚至在
\uuuu webpack\uuu require\uuuuu
函数中设置了断点,它们没有被触发。因此,我的模块都不是必需的/导入的

Webpack确实构建了模块,我在控制台的
纱线测试
命令(运行
karma start
)的输出中看到了这一点:

这是我的结构/配置

结构:

-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
    })
}
callback: function(){window.__karma__.start()}
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);
    });
}

当我的测试运行时,我执行了
0/0错误(0.001秒/0秒)
对我来说,这是一个与
优化相关的问题。分割块
。在我将其从karma网页包配置中删除后,找到了我的测试。

您需要输入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
    })
}
callback: function(){window.__karma__.start()}

最后解决了我自己的问题,很抱歉在更新答案时出现延迟,因为原来的帖子


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

我在更新网页5时遇到了同样的问题。测试执行:0个,共0个。在准备请求支持时,我创建了一个回购协议,并在这里找到了解决方案

解决方法非常简单。您需要像这样禁用分块:

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

默认情况下,karma webpack已启用分块。感谢约翰的提示()

你找到解决办法了吗?我也有同样的问题。