Karma reload debug.html on test file changes - javascript

When running Karma with autoWatch: true and singleRun: false, any change to my unit test files causes the tests to be re-run, and refreshes the Karma webpage at localhost:9876:
The problem is that the page athttp://localhost:9876/debug.html (the page you reach by clicking the DEBUG button) doesn't autorefresh, which is a pity since it prints more detailed information to the browser console and allows you to use breakpoints.
Is there a way to auto-refresh http://localhost:9876/debug.html on test file changes, and not just http://localhost:9876? I read through Karma's configuration file page and couldn't find any options for this. Setting up this page to auto-reload through means outside of Karma is perfectly acceptable.
Edit: Here's my karma.config.js file:
var webpack = require('webpack');
var path = require('path');
var environment = getEnvironment();
function getEnvironment() {
console.log('NODE_ENV: ' + process.env.NODE_ENV);
if(process.env.NODE_ENV === 'dev') {
return {
browsers: ['Chrome'],
singleRun: false
};
}
else if(process.env.NODE_ENV === 'staging') {
return {
browsers: ['PhantomJS2'],
singleRun: true
};
}
else if(process.env.NODE_ENV === 'production') {
return {
browsers: ['PhantomJS2'],
singleRun: true
};
}
return {};
}
module.exports = function (config) {
config.set({
browsers: environment.browsers,
singleRun: environment.singleRun,
frameworks: ['mocha'],
files: [
'tests.webpack.js',
{pattern: 'assets/img/*.jpg', watched: false, included: false, served: true, nocache: false},
{pattern: 'assets/img/*.png', watched: false, included: false, served: true, nocache: false},
{pattern: 'assets/img/*.gif', watched: false, included: false, served: true, nocache: false}
],
proxies: {
'/assets/img/': '/base/assets/img/'
},
preprocessors: {
'tests.webpack.js': ['webpack']
},
reporters: ['progress', 'clear-screen', 'dots'],
webpack: {
entry: {
app: ['./src/front.jsx']
},
devServer: {
historyApiFallback: true
},
output: {
// publicPath: 'http://localhost:8080/',
filename: './dist/[name].js'
},
module: {
loaders: [{
test: /\.(js|jsx)$/,
loaders: ['react-hot', 'jsx'],
include: /src/,
exclude: /(node_modules)/
},
{
test: /\.(js|jsx)$/,
include: /src/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets:['react', 'es2015']
}
},
{
test: /\.scss$/,
include: /src/,
exclude: /(node_modules)/,
loaders: ['style', 'css', 'sass']
},
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
{ test: /\.(woff|woff2)$/, loader:"url?prefix=font/&limit=5000" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" }
]
},
plugins: [
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
})
],
resolve: {
root: path.resolve(__dirname) + "/src/",
extensions: ['', '.js', '.jsx']
},
resolveLoader: {
root: path.join(__dirname, "node_modules")
}
},
webpackServer: {
noInfo: true
}
});
};
And tests.webpack.js:
var context = require.context('./src', true, /-test\.jsx?$/);
context.keys().forEach(context);

Set usePolling to true.
usePolling = true;
This works fine for me.

Related

How to build react js with only one chunk

I have a react js project and im actually dont know how to set webpack settings. After i run "npm run build" i get 10 js files names 1.js 2.js 3.js with main.js. I dont know how to bundle them. I searched some questions but couldnt solve it. Its not my first project in react but i didnt try to
build with webpack before. Thanks for helps.
My webpack.prod.js ;
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ResourceManifestPlugin = require('webpack-fivem-manifest');
module.exports = require('./webpack.common')({
mode: 'production',
// In production, we skip all hot-reloading stuff
entry: [path.join(process.cwd(), 'src/app.js')],
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
inject: true,
}),
new ResourceManifestPlugin(),
],
performance: {
assetFilter: assetFilename =>
!/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename),
},
});
My webpack.common.js :
const path = require('path');
const webpack = require('webpack');
module.exports = options => ({
mode: options.mode,
entry: options.entry,
output: {
path: path.resolve(process.cwd(), 'html'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.jsx?$/, // Transform all .js and .jsx files required somewhere with Babel
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
// Preprocess our own .css files
// This is the place to add your own loaders (e.g. sass/less etc.)
// for a list of loaders, see https://webpack.js.org/loaders/#styling
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader'],
},
{
// Preprocess 3rd party .css files located in node_modules
test: /\.css$/,
include: /node_modules/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(eot|otf|ttf|woff|woff2)$/,
use: 'file-loader',
},
{
test: /\.svg$/,
use: [
{
loader: 'svg-url-loader',
options: {
// Inline files smaller than 10 kB
limit: 10 * 1024,
noquotes: true,
},
},
],
},
{
test: /\.(jpg|png|gif)$/,
use: [
{
loader: 'url-loader',
options: {
// Inline files smaller than 10 kB
limit: 10 * 1024,
},
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
enabled: false,
// NOTE: mozjpeg is disabled as it causes errors in some Linux environments
// Try enabling it in your environment by switching the config to:
// enabled: true,
// progressive: true,
},
gifsicle: {
interlaced: false,
},
optipng: {
optimizationLevel: 7,
},
pngquant: {
quality: '65-90',
speed: 4,
},
},
},
],
},
{
test: /\.html$/,
use: 'html-loader',
},
{
test: /\.(mp4|webm)$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
},
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: `ifdef-loader`,
options: {
DEBUG: options.mode !== 'production',
version: 3,
'ifdef-verbose': true, // add this for verbose output
'ifdef-triple-slash': true, // add this to use double slash comment instead of default triple slash
},
},
],
},
],
},
plugins: options.plugins.concat([
// Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
// inside your code for any environment checks; Terser will automatically
// drop any unreachable code.
new webpack.EnvironmentPlugin({
NODE_ENV: 'development',
}),
]),
resolve: {
modules: ['src', 'node_modules'],
extensions: ['.js', '.jsx', '.react.js'],
},
});

Unexpected character '#' You may need an appropriate loader to handle this file type

This is what I get when I try to run webpack: the error I get is:
"ERROR in ./v3/app/styles/main.scss
Module parse failed: /Users/vovina/widget-login-react/v3/app/styles/main.scss Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type."
it can't resolve #import, any ideas on this?
my webpack config is as follow:
const childProcess = require('child_process')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const trimEnd = require('lodash/trimEnd')
const webpack = require('webpack')
const path = require('path')
const ENV = {
NODE_ENV: process.env.NODE_ENV,
API: 'https://accounts' + (process.env.NODE_ENV === 'prd' ? '' : '-'
+ process.env.NODE_ENV),
BUILD_VERSION: trimEnd(childProcess.execSync('git rev-list HEAD --
count').toString(), '\n'),
BUILD_DATE: trimEnd(childProcess.execSync('git log --format="%cd" -n
1').toString(), '\n'),
BUILD_COMMIT_ID: trimEnd(childProcess.execSync('git log --format="%h"
-n 1').toString(), '\n')
}
const prodLikeEnvironment = process.env.NODE_ENV === 'stg' ||
process.env.NODE_ENV === 'prd'
const CSS_MAPS = !prodLikeEnvironment
module.exports = {
entry: {
init: [
'./app/init.js'
],
login: [
'./app/login.js'
],
authentication: [
'./v3/app/authenticator.js'
],
common: [
'./app/common.js'
]
},
target: 'web',
output: {
path: path.join(__dirname, 'dist', process.env.NODE_ENV),
pathinfo: true,
publicPath: '/assets/widgets/login/v2/',
filename: '[name].bundle.js',
chunkFilename: '[id].bundle.js',
libraryTarget: 'umd'
},
resolve: {
alias: {
'react': 'preact-compat',
'react-dom': 'preact-compat'
},
modules: [
path.resolve('./app'),
path.resolve('./node_modules')
]
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: [/bower_components/, /node_modules/]
},
{
// Transform our own .(scss|css) files with PostCSS and CSS-modules
test: /\.(scss|css)$/,
include: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?modules&importLoaders=1&localIdentName=
[local]${process.env.CSS_MODULES_IDENT ||
'_[hash:base64:5]'}&sourceMap=${CSS_MAPS}`,
'postcss-loader',
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(scss|css)$/,
exclude: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?sourceMap=${CSS_MAPS}`,
`postcss-loader`,
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(svg|eot|woff|woff2?|ttf|otf)$/,
use: 'base64-font-loader'
},
{
test: /.json$/,
loader: 'json'
},
{
test: /\.jpe?g$|\.gif$|\.png$/,
use: 'base64-image-loader'
},
{
test: /\.html?$/,
loader: 'html'
},
{
test: /\.js$/,
loader: 'strip-loader?strip[]=debug,strip[]=console.log,strip[]=console.debug,strip[]=console.info'
}
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
minimize: true
// postcss: [
// autoprefixer({ browsers: 'last 2 versions' })
// ]
}),
new CopyWebpackPlugin([
{ from: 'public' }
]),
new ExtractTextPlugin('[name].bundle.css'),
new webpack.DefinePlugin({
ENV: JSON.stringify(ENV),
// Only used for react prod bundle. Refer to ENV.NODE_ENV for business
logic
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
unsafe_comps: true,
properties: true,
keep_fargs: false,
pure_getters: true,
collapse_vars: true,
unsafe: true,
warnings: false,
screw_ie8: true,
sequences: true,
dead_code: true,
drop_debugger: true,
comparisons: true,
conditionals: true,
evaluate: true,
booleans: true,
loops: true,
unused: true,
hoist_funs: true,
if_return: true,
join_vars: true,
cascade: true,
drop_console: true
}
})
]
}
You are using the (scss|css) twice in your configuration file.
Remove that and use the code posted blow:
Before using, you must first npm install raw-loader.
I think you've already installed the sass-loader.
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw-loader'
},
// // css global which not include in components
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: 'raw-loader'
})
},
{
test: /\.scss$/,
include: helpers.root('src', 'app'),
use: ['raw-loader', 'sass-loader']
},
// // SASS global which not include in components
{
test: /\.scss$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: ['raw-loader', 'sass-loader']
})
}
Add my root()function.
var path = require('path');
var _root = path.resolve(__dirname, '..');
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [_root].concat(args));
}
exports.root = root;
Hope this will work.

Lazy Loading not work in WebPack Angular 2 project

I'm new to webPack and I have a problem with my project in Angular 2.
I'm trying to apply Lazy Loading on the modules, but I have always the same mistake for hours.
The error occurs when i need to load a child module. (During the rooting)
export const routes: Routes =
[
{ path: '', redirectTo: '/account', pathMatch: 'full' },
{ path: 'account', component: LoginComponent },
{ path: 'student', canLoad: [AuthGuard], loadChildren: './student.module/app.student.module#AppStudentModule' },
{ path: 'teacher', canLoad: [AuthGuard], loadChildren: './teacher.module/app.teacher.module#AppTeacherModule' },
{ path: 'administrative', canLoad: [AuthGuard], loadChildren: './secretary.module/app.secretary.module#AppSecretaryModule' },
{ path: 'unauthorized', component: PageUnauthorized },
{ path: 'terms', component: TermsComponent},
{ path: '**', component: PageNotFound }
];
I show you my current configuration:
My webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeJsPlugin = require('optimize-js-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
const root = path.join.bind(path, path.resolve(__dirname));
// Webpack Config
const webpackConfig = {
entry: {
app: './src/main.ts',
polyfills: './src/polyfills.ts',
vendor: './src/vendor.ts'
},
output: {
publicPath: '/public/js',
path: path.resolve(__dirname, './public/js')
},
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
root('./src'), // location of your src
{} // a map of your routes
),
new webpack.ProvidePlugin({
'lodash': 'lodash',
'moment': 'moment',
'moment-timezone': 'moment-timezone',
'angular2-mdl': 'angular2-mdl',
'jquery': 'jquery'
}),
new CopyWebpackPlugin([ { from: 'src/assets/i18n', to: '/assets/i18n' } ]),
new ExtractTextPlugin('../css/styles.css')
],
module: {
loaders: [
{
test: /\.ts$/,
loaders: [
'awesome-typescript-loader',
'angular2-router-loader',
'angular2-template-loader'
]
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader?minimize=true'
}),
include: [root('assets', 'css'), /node_modules/]
},
{
test: /\.scss$/,
loader: 'raw-loader!sass-loader'
},
{test: /\.html$/, loader: 'raw-loader'},
{ test: /\.(png|jpg|woff|woff2|eot|ttf|TTF|svg)$/, loader: 'url-loader?limit=100000' }
]
}
};
const defaultConfig = {
devtool: 'source-map',
output: {
filename: '[name].js',
sourceMapFilename: '[name].map',
chunkFilename: '[name]-chunk.js'
},
resolve: {
extensions: [ '.ts', '.js' ],
modules: [ path.resolve(__dirname, 'node_modules') ]
},
node: {
global: true,
crypto: 'empty',
__dirname: true,
__filename: true,
process: true,
Buffer: false,
clearImmediate: false,
setImmediate: false
}
};
const commonConfig = webpackMerge(defaultConfig, webpackConfig);
const prodConfig = {
devtool: 'source-map',
plugins: [
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
sequences : true, // join consecutive statemets with the “comma operator”
properties : true, // optimize property access: a["foo"] → a.foo
dead_code : true, // discard unreachable code
drop_debugger : true, // discard “debugger” statements
unsafe : false, // some unsafe optimizations (see below)
conditionals : true, // optimize if-s and conditional expressions
comparisons : true, // optimize comparisons
evaluate : true, // evaluate constant expressions
booleans : true, // optimize boolean expressions
loops : true, // optimize loops
unused : true, // drop unused variables/functions
hoist_funs : true, // hoist function declarations
hoist_vars : false, // hoist variable declarations
if_return : true, // optimize if-s followed by return/continue
join_vars : true, // join var declarations
cascade : true, // try to cascade `right` into `left` in sequences
side_effects : true, // drop side-effect-free statements
warnings : true, // warn about potentially dangerous optimizations/code
},
output: {
comments: false,
space_colon: false
}
}),
new OptimizeJsPlugin({
sourceMap: false
}),
new webpack.optimize.OccurrenceOrderPlugin()
]
};
const testConfig = {
devtool: 'inline-source-map',
module: {
rules: [
{test: /\.scss$/, loaders: ['raw-loader', 'postcss-loader', 'sass-loader'], exclude: [/\.global\.scss$/, /node_modules/]},
{test: /\.global\.scss$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'], exclude: [/node_modules/]},
{test: /\.css$/, loaders: ['style-loader', 'css-loader'], include: [/node_modules/]},
{test: /\.css$/, loaders: ['to-string-loader', 'css-loader'], exclude: [/node_modules/]},
{test: /\.html$/, loader: 'raw-loader'},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
name: '../fonts/[name].[ext]',
publicPath: '/fonts/'
}
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
options: {
name: '../fonts/[name].[ext]',
publicPath: '/fonts/'
}
},
{
test: /\.ts$/,
use: [
{
loader: 'awesome-typescript-loader',
query: {
// use inline sourcemaps for "karma-remap-coverage" reporter
sourceMap: false,
inlineSourceMap: true,
compilerOptions: {
// Remove TypeScript helpers to be injected
// below by DefinePlugin
removeComments: true
}
},
},
'angular2-template-loader'
],
exclude: [/\.e2e\.ts$/]
},
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader',
exclude: [/spec-bundle\.js/, /node_modules/]
},
{
enforce: 'post',
test: /\.(js|ts)$/,
loader: 'istanbul-instrumenter-loader',
exclude: [
/spec-bundle\.js/,
/\.(e2e|spec)\.ts$/,
/node_modules/
]
}
]
}
};
const devConfig = {
devtool: 'cheap-module-source-map',
module: {
loaders: [
{
test: /\.ts$/,
loader: 'tslint-loader',
options: {
configFile: 'tslint.json'
},
exclude: [/\.(spec|e2e)\.ts$/, /node_modules/]
},
]
}
};
switch (process.env.NODE_ENV) {
case 'staging':
case 'production':
module.exports = webpackMerge(commonConfig, prodConfig);
break;
case 'test':
module.exports = webpackMerge(commonConfig, testConfig);
break;
case 'development':
default:
module.exports = webpackMerge(commonConfig, devConfig);
}
And this is my tsconfig.json:
{
"angularCompilerOptions": {
"entryModule": "src/app.module#AppModule",
"genDir": "./ngfactory",
"debug": false
},
"awesomeTypescriptLoaderOptions": {
"useWebpackText": true
},
"buildOnSave": false,
"compileOnSave": false,
"compilerOptions": {
"allowUnusedLabels": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"es6",
"dom"
],
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": false,
"noImplicitReturns": true,
"outDir": "public/js",
"rootDir": ".",
"sourceMap": true,
"suppressImplicitAnyIndexErrors": true,
"target": "ES5",
"typeRoots": [
"node_modules/#types"
],
"types": ["node", "jasmine"]
},
"exclude": [
"node_modules",
"public"
]
}
And so i have this error:
Please help me!!
Thanks

Coverage reports with karma and a mix of javascript and typescript src files

I have a project where I use webpack for development/testing and karma as my test runner. This project has source files written half in js and half in ts/tsx. The test suite is written completely in js. I currently use karma-coverage, which shows coverage reports for all my js source files, but it does not support typescript files. All my tests run, there is no problem there, I just would like coverage reports for all my test files. Can anyone point me in the right direction?
Here is my karma.conf.js if this helps.
'use strict';
const webpackCfg = require('./webpack.config')('test');
module.exports = function karmaConfig(config) {
config.set({
browsers: ['Chrome'],
files: [
'test/loadtests.js'
],
port: 8080,
captureTimeout: 60000,
frameworks: [
'mocha',
'chai',
'sinon'
],
client: {
mocha: {}
},
singleRun: true,
reporters: ['mocha', 'coverage', 'junit'],
mochaReporter: {
output: 'autowatch'
},
preprocessors: {
'test/loadtests.js': ['webpack', 'sourcemap']
},
webpack: webpackCfg,
webpackServer: {
noInfo: true
},
junitReporter: {
outputDir: 'coverage',
outputFile: 'junit-result.xml',
useBrowserName: false
},
coverageReporter: {
dir: 'coverage/',
watermarks: {
statements: [70, 80],
functions: [70, 80],
branches: [70, 80],
lines: [70, 80]
},
reporters: [
{ type: 'text' },
{
type: 'html',
subdir: 'html'
},
{
type: 'cobertura',
subdir: 'cobertura'
},
{
type: 'lcovonly',
subdir: 'lcov'
}
]
}
});
};
And the relevant part of my webpack test config
{
devtool: 'inline-source-map',
externals: {
cheerio: 'window',
'react/lib/ExecutionEnvironment': true,
'react/addons': true,
'react/lib/ReactContext': true,
},
module: {
preLoaders: [
{
test: /\.(js|jsx)$/,
loader: 'isparta-loader',
include: [
this.srcPathAbsolute
]
}
],
loaders: [
{
test: /\.cssmodule\.css$/,
loaders: [
'style',
'css?modules&importLoaders=1&localIdentName=[name]-[local]-[hash:base64:5]'
]
},
{
test: /^.((?!cssmodule).)*\.css$/,
loader: 'null-loader'
},
{
test: /\.(sass|scss|less|styl|png|jpg|gif|mp4|ogg|svg|woff|woff2)$/,
loader: 'null-loader'
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
loader: ['babel', 'ts-loader']
},
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
query: {
presets: ['airbnb']
},
include: [].concat(
this.includedPackages,
[
this.srcPathAbsolute,
this.testPathAbsolute
]
)
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"test"'
})
]
}
After a couple days of soul and google searching amongst hundreds of browser tabs, I have found a working solution. This is using TypeScript 2.x and Webpack 2.x. test.js is my entry point. It could just as easily be test.ts (and it will be eventually). In that entry point, I load my *.spec.js and *.spec.ts files. And then those files import whichever source they need to test from. I have put all the webpack config in the karma.conf.js so it's easier to see:
let myArgs = require('yargs').argv;
let path = require('path');
let webpack = require('webpack');
module.exports = function(config) {
const REPORTS_PATH = myArgs.reportsPath ? myArgs.reportsPath :path.join(__dirname, 'build');
config.set({
basePath: '',
frameworks: ['jasmine', 'es6-shim'],
files: [
'./test.js'
],
exclude: [],
reporters: ['progress', 'spec', 'coverage', 'junit', 'coverage-istanbul'],
preprocessors: {
'./test.js': ['webpack', 'sourcemap']
},
webpackServer: {
noInfo: true // prevent console spamming when running in Karma!
},
webpack: {
devtool: 'inline-source-map',
resolve: {
modules: [
path.resolve('./node_modules'),
path.resolve('./')
],
extensions: ['.js', '.ts', '.css', '.scss']
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
],
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
use: 'source-map-loader',
exclude: [/node_modules/]
},
{
test: /\.ts$/,
use: [{
loader: 'awesome-typescript-loader',
options: {
module: 'commonjs'
},
}]
},
{
test: /\.js$/,
use: [{
loader: 'awesome-typescript-loader',
options: {
entryFileIsJs: true,
transpileOnly: true
}
}],
exclude: [/node_modules/],
},
{
enforce: 'post',
test: /\.(js|ts)$/,
use: [{
loader: 'istanbul-instrumenter-loader',
options: {
esModules: true
}
}],
exclude: [/node_modules/, /\.spec\.(js|ts)$/, /test/]
},
{ test: /\.html/, use: 'raw-loader' },
{ test: /\.(s)?css$/, use: 'null-loader' },
{ test: /\.(png|jpg|jpeg|gif|svg|pdf)$/, use: 'null-loader' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'null-loader' },
{ test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'null-loader' },
{ test: /\.json$/, use: 'null-loader' }
]
}
},
coverageReporter: {
type: 'in-memory'
},
coverageIstanbulReporter: {
//TODO: Figure out why the 'html' reporter blows up with istanbul-reports (something with absolute path copying files)
reports: ['text-summary', 'cobertura'],
// base output directory
dir: REPORTS_PATH,
fixWebpackSourcePaths: true,
'report-config': {
cobertura: {
file: 'coverage.xml'
},
'text-summary': {
file: null
}
}
},
junitReporter: {
outputDir: `${REPORTS_PATH}/junit/`,
outputFile: 'jasmine-results.xml'
},
// Hide webpack build information from output
webpackMiddleware: {
stats: {
chunkModules: false,
colors: true
},
noInfo: 'errors-only'
},
colors: true,
logLevel: config.LOG_ERROR,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
autoWatchBatchDelay: 400
});
};
So, the key pieces here are awesome-typescript-loader, karma-coverage-istanbul-reporter, source-map-loader, and in the tsconfig.json, you want to set these in compilerOptions:
"inlineSourceMap": true,
"sourceMap": false,
I indicated a TODO about the html report. It DOES work but I couldn't get it to output to a custom directory (subdir) with TypeScript files as a part of it. JavaScript only worked fine. Could be a windows-specific problem with istanbul-reports. If you add html to the reports array under coverageIstanbulReporter, you should see it in your project dir but may have problems putting it in REPORTS_PATH.
It's also worth noting that I had a lot of luck using karma-remap-coverage instead of karma-coverage-istanbul-reporter but the former would not correctly generate cobertura reports for coverage which is what I needed for Jenkins.

Why doesn't my karma support for...of statement?

I have setup karma as my unit test framework. But it doesn't compile below code:
let {btnData} = this.props
let buttons = []
for (let btn of btnData) {
btn = {...btnCategories[btn.type], ...btn}
buttons.push(btn)
}
I got below error on the line of for loop. Why doesn't it recognise for...of statement?
Can't find variable: Symbol
Below is my karma config file. My project includes webpack, reactjs and use karma, mocha, chai, enzyme as test libraries.
var path = require('path')
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai'],
files: [
'../test/**/*.js'
],
preprocessors: {
// add webpack as preprocessor
'../src/**/*.js': ['webpack', 'sourcemap'],
'../test/**/*.js': ['webpack', 'sourcemap'],
'../src/**/*.less': ['webpack', 'sourcemap']
},
webpack: { //kind of a copy of your webpack config
devtool: 'inline-source-map', //just do inline source maps instead of the default
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/,
query: {
presets: ['airbnb']
}
},
{
test: /\.json$/,
loader: 'json',
},{
test: /\.less$/,
loader: "style!css!less",
},
]
},
externals: {
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true,
'react/addons': true
},
resolve: {
alias: {
app: path.join(__dirname, '../src/js')
}
}
},
webpackServer: {
noInfo: true //please don't spam the console when running in karma!
},
plugins: [
'karma-webpack',
'karma-jasmine',
'karma-sourcemap-loader',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-mocha',
'karma-chai',
'karma-mocha-reporter'
],
babelPreprocessor: {
options: {
presets: ['airbnb']
}
},
reporters: ['mocha'],
// reporter options
mochaReporter: {
colors: {
success: 'blue',
info: 'bgGreen',
warning: 'cyan',
error: 'red'
},
symbols: {
success: '+',
info: '#',
warning: '!',
error: 'x'
}
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
})
};

Categories

Resources