Reputation: 5169
I'm using karma-webpack and babel in a project to write ES6 tests with executed with Jasmine and import ES6 classes used by my unit tests.
I noticed that I wasn't able to export a class written in ES6 to use it in my unit tests. Here is my code:
Hello.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));
});
When I run karma start
, the console.log
displays:
PhantomJS 1.9.8 (Mac OS X 0.0.0) LOG LOG: 'Hello: undefined'
But I noticed that if I replace the code in the Hello.js
file by:
const Hello = {'a': 'b'};
export default Hello;
It works when I run karma start
:
PhantomJS 1.9.8 (Mac OS X 0.0.0) LOG LOG: 'Hello: {"a":"b"}'
Here is my 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
});
};
My project structure:
karma.conf.js
tests/
Hello.js
Hello.test.js
Any suggestion?
Upvotes: 2
Views: 985
Reputation: 36408
As per the ECMAScript specification of JSON.stringify
:
Values that do not have a JSON representation (such as undefined and functions) do not produce a String. Instead they produce the undefined value.
Since classes are just syntactic sugar over functions, calling JSON.stringify(class Foo {})
will yield undefined
.
Try doing console.log(Hello)
or console.log(Hello.name)
, which should yield, respectively, [Function: Hello]
and Hello
.
Upvotes: 1