【问题标题】:Cannot import class using karma-webpack and babel. The imported class is undefined无法使用 karma-webpack 和 babel 导入类。导入的类未定义
【发布时间】:2015-10-31 12:01:12
【问题描述】:

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

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

你好.js

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

Hello.test.js

"use strict";

import Hello from './hello';

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

当我运行karma start 时,console.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

有什么建议吗?

【问题讨论】:

  • 我想知道您期望的输出是什么?
  • 我希望有更明确的行为。例如。只是一个字符串“Function”或“Class”,只是为了知道这个类已经被很好地定义了。我不知道这样的行为是否可行。
  • JSON.stringify 接受第二个参数,一个函数,用于序列化数据结构中的每个值。您可以使用它来实现此类功能。但是,如果您描述的是默认行为,那就不好了。 JSON 的接收方无法知道数据是否包含字符串"Function",或者这是否是某个本机函数。 IE。真实数据与其 JSON 表示之间不会存在 1:1 映射。
  • 是的,这是有道理的。在这种情况下,我不应该使用JSON.stringify()。感谢您的帮助!

标签: javascript karma-runner ecmascript-6 webpack babeljs


【解决方案1】:

按照JSON.stringifyECMAScript specification

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

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

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

【讨论】:

  • 好收获!我不知道JSON.stringify 的这种行为。非常感谢,你拯救了我的一天。