繁体   English   中英

无法使用 karma-webpack 和 babel 导入类。 导入的类未定义

[英]Cannot import class using karma-webpack and babel. The imported class is undefined

我在一个项目中使用 karma-webpack 和 babel 来编写 ES6 测试,并使用 Jasmine 执行并导入我的单元测试使用的 ES6 类。

我注意到我无法导出用 ES6 编写的类以在我的单元测试中使用它。 这是我的代码:

你好.js

export default class Hello {
  constructor() {
    this.a = 'b';
  }
}

你好.test.js

"use strict";

import Hello from './hello';

describe(" hello unit tests", function () {
  console.log('Hello: ' + JSON.stringify(Hello));
});

当我运行karma startconsole.log显示:
PhantomJS 1.9.8 (Mac OS X 0.0.0) LOG LOG: 'Hello: undefined'

但我注意到,如果我将Hello.js文件中的代码替换为:

const Hello = {'a': 'b'};

export default Hello;

当我运行karma start时它有效:
PhantomJS 1.9.8 (Mac OS X 0.0.0) LOG LOG: 'Hello: {"a":"b"}'

这是我的karma.conf.js

var webpack = require("webpack");

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ["jasmine"],
    files: [
        "./tests/**/*.test.js"
    ],
    preprocessors: {
        "./tests/**/*.js": ["webpack",  "sourcemap"]
    },
    webpack: {
        module: {
            loaders: [{
              test: /\.js/,
              exclude: /(node_modules)/,
              loader: 'babel-loader'
            }]
        },
        devtool: "inline-source-map",
    },
    webpackMiddleware: {
        progress: false,
        stats: false,
        debug: true,
        noInfo: true,
        silent: true 
    },
    plugins: [
        require("karma-webpack"),
        require("karma-jasmine"),
        require("karma-phantomjs-launcher"),
        require("karma-sourcemap-loader"),
        require("karma-spec-reporter"),
    ],
    specReporter: {maxLogLines: 5},
    reporters: ["spec"],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ["PhantomJS"],
    singleRun: true
  });
};

我的项目结构:

karma.conf.js
tests/
  Hello.js
  Hello.test.js

有什么建议吗?

根据JSON.stringifyECMAScript 规范

没有 JSON 表示的值(例如 undefined 和函数)不会生成字符串。 相反,它们产生未定义的值。

由于类只是函数的语法糖,调用JSON.stringify(class Foo {})将产生undefined

尝试执行console.log(Hello)console.log(Hello.name) ,它们应该分别产生[Function: Hello]Hello

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM