如何使用 Karma 和 React 16.2.0 修复此错误?

Posted

技术标签:

【中文标题】如何使用 Karma 和 React 16.2.0 修复此错误?【英文标题】:How Can I Fix this Error with Karma & React 16.2.0? 【发布时间】:2018-06-28 15:30:26 【问题描述】:

我有这个 Karma 配置(使用 React 16.2.0):

const isArray = require('lodash/lang/isArray');
const merge = require('lodash/object/merge');
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');

/**
* Base karma configuration.
* The properties stated here will be common for every other configuration. This will serve as a
* point of reuse for a local coverage configuration, and a different CI coverage configuration.
* @type Object
*/

const ALL_FILES = [
//    'test/react-throw-on-error.js',
    './node_modules/phantomjs-polyfill/bind-polyfill.js',
    './node_modules/jquery/dist/jquery.js',
    'test/allTests.js'
];

var baseConf = 
    plugins: [
        'karma-coverage',
        'karma-webpack',
        'sass-loader',
        'karma-chrome-launcher',
        'karma-phantomjs-launcher',
        'karma-mocha-reporter',
        'karma-mocha'
    ],

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

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

    // list of files / patterns to load in the browser
    files: ALL_FILES,


    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    preprocessors: 
        'test/allTests.js': ['webpack']
    ,

    client: 
        captureConsole: true
    ,

    webpack: 
        plugins: [
            new CaseSensitivePathsPlugin(),
            new ExtractTextPlugin('style.css'),
            new webpack.DefinePlugin(
                '__ENVIRONMENT__': '"DEV"',
                '__DEBUG_MODE__': true,
                '__BASE_HOST__': JSON.stringify(process.env.BASE_HOST || '') ,
                '__MOCK_ALL_ENDPOINTS__': JSON.stringify(process.env.MOCK_ALL_ENDPOINTS || ''),
                '__MOCKED_ENDPOINTS__': JSON.stringify(process.env.MOCKED_ENDPOINTS || ''),
                '__PUBLIC_URL__': JSON.stringify(process.env.PUBLIC_URL || ''),
                '__REDIRECTED_ENDPOINTS__': JSON.stringify(process.env.REDIRECTED_ENDPOINTS || ''),
                '__LOG_API_ERRORS_REMOTELY__': JSON.stringify(process.env.LOG_API_ERRORS_REMOTELY || ''),
                '__SHOW_API_ERRORS__': JSON.stringify(process.env.SHOW_API_ERRORS || '')
            )
        ],
        module: 
            preLoaders: [
                
                    test: /\.jsx?$/,
                    exclude: /(node_modules)/,
                    loader: 'babel',
                    query: 
                        presets: ['react', ["es2015", "loose": true]],
                        plugins: ['array-includes'],
                        cacheDirectory: true
                    
                ,
                
                    test: /\.?css$/,
                    loader: ExtractTextPlugin.extract(
                        "style",
                        "css!sass")
                ,
                
                    test: /\.(png|jpg|gif)$/,
                    loader: 'url-loader?limit=8192'
                ,
                
                    test: /\.(otf|ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
                    loader: 'file-loader'
                ,
                
                    test: /\.json$/,
                    loader: 'json'
                

            ]
        ,
        resolve: 
            root: [path.resolve('src'), path.resolve('test')],
            modulesDirectories: ['node_modules'],
            alias: 
                commonsComponents: 'commons-components/build',
                commonsUtilities: 'commons-components/src/lib/utilities',
                stylesOpenBank: 'styles-openbank/src/styles/_base.scss',
                stylesOpenBankApp: 'styles-openbank/src/styles/_app.scss',
                stylesOpenBankBootstrap: 'styles-openbank/src/styles/_bootstrap.scss',
                stylesOpenBankAssests: 'styles-openbank/src/assets'
            
        ,

        externals: 
            'react/addons': true,
            'react-addons-test-utils': true,
            'react/lib/ExecutionEnvironment': true,
            'react/lib/ReactContext': true,
        ,

        babelPreprocessor: 
            options: 
                presets: ['airbnb']
            
        
    ,

    webpackMiddleware: 
        noInfo: true,
    ,

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

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

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

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

    // Increments how long will Karma wait for a message from a browser before disconnecting from it (in ms).
    browserNoActivityTimeout: 60000
;

/**
* Helper to provide lodash merge with deep array merging
*/
function customizer(objValue, srcValue) 
    if (isArray(objValue)) 
        return objValue.concat(srcValue);
    


/**
* Base Karma configuration for running a coverage analysis.
* Based on the base config, this one is an extension to add all data is needed for a coverage
* instrumentation. It is also a base config, as it will be reused in a local and a CI coverage task.
* @type Object
*/
var coverageConf = merge(, baseConf, 
    webpack: 
        isparta: 
            embedSource: true,
            noAutoWrap: true,
            babel: 
                presets: ['es2015', 'react']
            
        ,
        module: 
            preLoaders: [
                
                    test: /\.js$/,
                    include: path.resolve('src'),
                    loader: 'isparta-loader'
                
            ]
        
    ,
    coverageReporter: 
        type: 'lcov',
        dir: 'test/coverage/'
    ,

    reporters: ['coverage']
, customizer);

module.exports.baseConf = baseConf;
module.exports.coverageConf = coverageConf;

我收到以下控制台错误:

"message": "未捕获的 ReferenceError: 未定义插件\nat test/allTests.js:81672:8\n\nReferenceError: 未定义插件\n 在 Object.defineProperty.value (test/allTests.js:84455:18)\n 在 webpack_require (test/allTests.js:20:30)\n 在 test/allTests.js:81668:20\n 在 Object.defineProperty.value (test/allTests.js:81732:6)\n 在 webpack_require (test/allTests.js:20:30)\n 在对象处。 (test/allTests.js:79742:21)\n 在对象。 (test/allTests.js:80112:31)\n 在 webpack_require (test/allTests.js:20:30)\n 在对象处。 (test/allTests.js:77771:15)\n 在 webpack_require (test/allTests.js:20:30)", "str": "未捕获的 ReferenceError: 未定义插件\nat test/allTests.js:81672:8\n\nReferenceError: 未定义插件\n 在 Object.defineProperty.value (test/allTests.js:84455:18)\n 在 webpack_require (test/allTests.js:20:30)\n 在 test/allTests.js:81668:20\n 在 Object.defineProperty.value (test/allTests.js:81732:6)\n 在 webpack_require (test/allTests.js:20:30)\n 在对象处。 (test/allTests.js:79742:21)\n 在对象。 (test/allTests.js:80112:31)\n 在 webpack_require (test/allTests.js:20:30)\n 在对象处。 (test/allTests.js:77771:15)\n 在 webpack_require (test/allTests.js:20:30)"

这个错误的根源是什么?

【问题讨论】:

【参考方案1】:

react-addons-test-utils 与 React 16 不兼容。正如 npm 页面所说,TestUtils 已移至 react-dom/test-utils。见Facebook's test-utils docs。

【讨论】:

以上是关于如何使用 Karma 和 React 16.2.0 修复此错误?的主要内容,如果未能解决你的问题,请参考以下文章

使用Jasmine和karma对传统js进行单元测试

React.js + Summernote,如何导入 JavaScript 依赖库

Karma/Jasmine 在没有运行测试的情况下超时

如何安装和使用Karma-Jasmine

npm karma phantomJS undefined 不是构造函数

如何通过 Angular、Karma 和 Webpack 的单独文件拆分代码覆盖率?