使用ES2015与摩卡,业力和无头铬进行测试

问题描述 投票:2回答:2

我在为单页面应用程序设置测试环境时遇到问题。我可以通过karma和mocha使用无头chrome运行我的测试但是我不能用ES6语法编写测试。

我当前的启动命令是

karma start --browsers ChromeHeadless karma.config.js --single-run

我的karma.config.js

module.exports = function(config) {
    config.set({
        frameworks: ['mocha', 'chai'],
        files: ['test/**/*spec.js'],
        reporters: ['nyan'],
        port: 9876,  // karma web server port
        colors: true,
        logLevel: config.LOG_INFO,
        browsers: ['ChromeHeadless'],
        autoWatch: true,
        singleRun: false, // Karma captures browsers, runs the tests and exits
        concurrency: Infinity,
    })
}

我能够编写正常的测试但不能在这里使用ES6语法。当我尝试导入一些反应组件时,我收到此错误:

HeadlessChrome 0.0.0 (Linux 0.0.0)
Uncaught SyntaxError: Unexpected token import
at http://localhost:9876/base/test/components.spec.js?b89d2ba6de494310860a60ad2e9e25aea5eb3657:2

所以我必须先设置babel来编译我的测试文件。当我尝试在我的业力配置中使用compilers: ['js:babel-core/register']时,它不会起作用。

我也看到compilers似乎很快就是deprecated所以我也尝试了require: ['babel-core/register'],但它仍然不会编译使用ES6作为我的测试文件。

知道如何配置我的业力文件来用ES6编写我的测试吗?

以防万一重要。这是我的webpack.config.js

const path = require('path');
const ServiceWorkerWebpackPlugin =  require('serviceworker-webpack-plugin');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
    template: './src/index.html',
    filename: 'index.html',
    inject: 'body'
});

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve('dist'),
        filename: 'index_bundle.js'
    },
    module: {
        loaders: [
            {test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/},
            {test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/}
        ]
    },
    plugins: [
        new ServiceWorkerWebpackPlugin({
            entry: path.join(__dirname, 'src/sw.js'),
        }),
        HtmlWebpackPluginConfig
    ],
    devServer: {
        hot: false,
        inline: false,
        historyApiFallback: true
    }

};
mocha tdd karma-runner chai google-chrome-headless
2个回答
1
投票

为了使事情更清楚,这里是一个示例项目(它完全可以运行,你可以填写文件并玩游戏)。仅举两件事:我使用jamsine而不是mocha和真正的“Chrome”浏览器而不是无头。通过npm run test命令运行。

文件结构

/
    karma.conf.js
    package.json
    sample.js
    sampleTest.js
    webpack.test.config.js

karma.conf.js

// Karma configuration
module.exports = function(config) {
  config.set({
    // 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: ['jasmine'],
    // list of files / patterns to load in the browser
    files: ['*Test.js'],
    // list of files to exclude
    exclude: [],
    // preprocess matching files before serving them to the browser
    preprocessors: {
        '*Test.js': [ 'webpack'] //preprocess with webpack
    },
    // test results reporter to use
    reporters: ['progress'],
    // setting up webpack configuration
    webpack: require('./webpack.test.config'),
    // web server port
    port: 9876,
    // enable / disable colors in the output (reporters and logs)
    colors: true,
    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,
    // start these browsers
    browsers: ['Chrome'],
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,
    // Concurrency level how many browser should be started simultaneous
    concurrency: Infinity
  })
}

package.json(只有相关的东西):

{
    "scripts": {
        "test": "node_modules/karma/bin/karma start karma.conf.js"
    },
    "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-env": "^1.6.1",
        "jasmine-core": "^2.8.0",
        "karma": "^2.0.0",
        "karma-chrome-launcher": "^2.2.0",
        "karma-jasmine": "^1.1.1",
        "karma-webpack": "^2.0.9",
        "webpack": "^3.10.0"
    }
}

sample.js

export default function(data){
        return data;
}

sampleTest.js

import sample from 'sample';

describe('Sample', function(){

    it('is defined', function(){
        expect(sample).toBeDefined();
    });

    it('returns argument', function(){
        expect(sample(0)).toBe(0);
    })
});

webpack.test.config.js:

module.exports = { 
    module: {
        rules: [
            {
                test: /tests\/.*\.js$/,
                exclude: /(node_modules)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['babel-preset-env']
                    }
                }
            }
        ]
    },
    resolve: {
        modules: ["node_modules", './'],
        extensions: [".js"]
    }
};

Karma的webpack插件用于通知业者它应该使用webpack和特定的webpack配置准备文件,然后再将它们发送到浏览器。

请注意关键点:

  • 在karma.conf.js中测试文件模式
  • 模式来预处理文件(应该与上面的模式匹配)
  • karma.conf.js文件中的webpack条目
  • webpack.test.config.js中的模块条目

附:我个人不使用单独的文件模式,我使用一个单独的文件(名为tests.webpack.js)来定义查找测试文件的方法:

//make sure you have your directory and regex test set correctly
var context = require.context('.', true, /.*Test\.js$/i); 
context.keys().forEach(context);

并且在karma.conf.js(路径与上面的示例项目无关):

files: [
    'tests/tests.webpack.js',
],
preprocessors: {
    './tests/tests.webpack.js': [ 'webpack'] //preprocess with webpack
}

0
投票

您需要使用babel-plugin-transform-es2015-modules-commonjs插件转换commonjs模块中的ESModule

在你的.babelrc文件中:

{
    "plugins": [
        "transform-es2015-modules-commonjs"
    ]
}

更新:您可以在webpack配置中设置插件:

{
     loader: 'babel-loader',
     options: {
          presets: ['@babel/preset-env'],
          plugins: [require('@babel/plugin-transform-es2015-modules-commonjs')]
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.