Can not load reporter "coverage-istanbul" - karma-jasmine

I am trying to run code coverage using https://webpack.js.org/loaders/istanbul-instrumenter-loader/
Here is the karma.conf.js
var testWebpackCfg = require('../webpack/webpack.config.test.js');
module.exports = function(config) {
config.set({
basePath: '../../',
frameworks: ['jasmine'],
plugins: [ 'karma-webpack', 'karma-jasmine-jquery', 'karma-jasmine', 'karma-chrome-launcher','karma-firefox-launcher', 'karma-coverage','karma-spec-reporter', 'karma-jasmine-html-reporter'],
preprocessors: {
'client/test/index.js': ['webpack']
},
reporters: [ 'spec', 'coverage-istanbul'],
coverageIstanbulReporter: {
reports: [ 'text-summary' ],
dir: './coverage',
fixWebpackSourcePaths: true
},
files: [
'client/test/index.js'
],
webpack: testWebpackCfg,
// web server port
port: 9876,
runnerPort: 9100,
urlRoot: '/',
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
browsers: ['Chrome'],
singleRun: true
});
};
Webpack config
{
test: /\.js$/i,
exclude: [
paths.appNodeModules
],
use: [
{
loader: require.resolve('babel-loader'),
options: {
presets: ['#babel/preset-env']
}
},
{
loader: require.resolve('istanbul-instrumenter-loader'),
options: {
esModules: true
}
}
]
}
On running the Karma I see this error
'Can not load reporter "coverage-istanbul", it is not registered!
Perhaps you are missing some plugin?'

The error got resolved by adding karma-coverage-istanbul-reporter in the karma config plugin.
npm i karma-coverage-istanbul-reporter --save-dev
karma.conf.js
{
...
plugins: ['karma-coverage-istanbul-reporter']
...
}

I faced the same problem after upgrading to Angular 14 from 11. Adding the Istanbul reporter compared to the Karma reporter solved my issue.
So simply add coverage-istanbul to your reporters in karma.conf.js
Like:
reporters: ['progress', 'kjhtml', 'coverage-istanbul'],
For example:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular'],
plugins: [
...
],
client: {
...
},
coverageIstanbulReporter: {
...
},
reporters: ['progress', 'kjhtml', 'coverage-istanbul'],
})
}

Nishant gives the essential answer, but I found I also got this message when I had not specified the karma config file explicitly, as per this answer:
cant get junit running with Karma

Related

Error evaluating function `ceil`: argument must be a number

On OSX, after I installed all of dependencies by yarn install, The webpack bundle's output keeps showing the error Error evaluating function ceil: argument must be a number.
I have no idea why this happen but it works on my linux machine with the same package.json
Some info:
webpack: "5.56.0"
less: "^4.1.2"
less-loader: "^10.0.1"
Here is my less-loader config:
{loader: "less-loader"}
It looks like the there is a change of the default options of less based on what I've found in here
https://lesscss.org/usage/#less-options-math
The solution is adding the option for less-loader in webpack config as following:
{
loader: "less-loader",
options: {
lessOptions: {
math: 'always' // <=== add this
}
}
}
Also you should change => strictMath: false
Example (my file config-overrides.js):
const addLessLoader = require("customize-cra-less-loader");
module.exports = override(
addLessLoader({
cssLoaderOptions: {
sourceMap: true,
modules: {
localIdentName: "[hash:base64:8]",
},
},
lessLoaderOptions: {
lessOptions: {
math: "always",
modifyVars: { "#primary-color": "#2a4365" },
javascriptEnabled: true,
strictMath: false,
},
},
})
);

Serverless Webpack generates empty files in ZIP package

I'm facing with a rather annoying and frustrating anomaly with Serverless + Webpack generating empty files in the .serverless/<package>.zip.
Config
serverless.yml
...
webpack:
webpackConfig: ./webpack.config.js
includeModules: true
...
webpack.config.js
const slsw = require("serverless-webpack")
const nodeExternals = require("webpack-node-externals")
// const CopyPlugin = require("copy-webpack-plugin")
module.exports = {
entry: slsw.lib.entries,
target: 'node',
// Generate sourcemaps for proper error messages
devtool: 'source-map',
// Since 'aws-sdk' is not compatible with webpack,
// we exclude all node dependencies
externals: [nodeExternals()],
mode: slsw.lib.webpack.isLocal ? "development" : "production",
optimization: {
// We do not want to minimize our code.
minimize: false
},
performance: {
// Turn off size warnings for entry points
hints: false
},
// node: false,
// devtool: 'inline-cheap-module-source-map',
// Run babel on all .js files and skip those in node_modules
module: {
rules: [
{
test: /\.js$/,
include: __dirname,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
[
'#babel/preset-env',
{
targets: { node: '12' },
useBuiltIns: 'usage',
corejs: 3,
},
],
],
},
},
],
},
],
},
plugins: [
// TODO
// new CopyPlugin([
// 'path/to/specific/file',
// 'recursive/directory/**',
// ]),
],
};
Additional Data
Serverless-Webpack Version: "serverless-webpack": "^5.3.5",
Webpack version: "webpack": "4.44.2",
Serverless Framework Version: 1.83.2
Operating System: MacOS
I have tried other version combinations too: Serverless 2.20, webpack 5.17.0, copy-webpack-plugin 7.0.0
Why empty files in ZIP?? 🤯
Update:
I have just tried to run sls package in one of the example projects with same result, empty files in ZIP.
Thanks.
I downgraded nodejs from 15.7.0 to 15.4.0 and it's working fine now.
Solution: downgrade Node JS from version 15 to 13. (Did not try 14.)
Use nvm to manage different versions of the node.
The issue was happening for me with node version v15.8.0. Resolved by downgrading system version to v14.15.5 using nvm.
Reference - https://forum.serverless.com/t/empty-files-in-uploaded-zip/13777

How to distinguish files which have the same name but in different sub-folders in sourcemap?

In my VUE project, there are several templates which have the same filename but located in different source sub-folders. I'm using webpack 3.12 to build it, and the devtool set to 'cheap-module-eval-source-map'.
After I run webpack-dev-server 2.11.1 to debug it, all template source files are put into the root folder 'webpack://' of the browser's sourcemap, so ONLY one of these files can exist, others are lost, I can't debug them.
Is there a way to make these files co-existing in the sourcemap?
module.exports = {
plugins: [
new VueLoaderPlugin()
],
context: path.resolve(__dirname, '../'),
entry: {
app: ['babel-polyfill', './src/main.js']
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production' ?
config.build.assetsPublicPath : config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src'),
}
},
devtool: 'cheap-module-eval-source-map',
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [{
from: /.*/,
to: path.posix.join(config.dev.assetsPublicPath, 'index.html')
}, ],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay ?
{
warnings: false,
errors: true
} :
false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
}
}
At last, I changed 'cheap-module-eval-source-map' to 'module-eval-source-map', the relative path of source files are kept.
I've read the official document of devtool, it says "it doesn't have column mappings, it only maps line numbers." if "cheap" mode used, I don't understand why the relative path is discarded.
eval-cheap-source-map - Similar to eval-source-map, each module is executed with eval(). It is "cheap" because it doesn't have column
mappings, it only maps line numbers. It ignores SourceMaps from
Loaders and only display transpiled code similar to the eval devtool.
eval-cheap-module-source-map - Similar to eval-cheap-source-map, however, in this case Source Maps from Loaders are processed for
better results. However Loader Source Maps are simplified to a single
mapping per line.
This worked for me when using vue-cli-service serve: https://github.com/vuejs/vue-cli/issues/2978#issuecomment-577364101
In vue.config.js:
let path = require('path')
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'development') {
// See available sourcemaps:
// https://webpack.js.org/configuration/devtool/#devtool
config.devtool = 'eval-source-map'
// console.log(`NOTICE: vue.config.js directive: ${config.devtool}`)
config.output.devtoolModuleFilenameTemplate = info => {
let resPath = path.normalize(info.resourcePath)
let isVue = resPath.match(/\.vue$/)
let isGenerated = info.allLoaders
let generated = `webpack-generated:///${resPath}?${info.hash}`
let vuesource = `vue-source:///${resPath}`
return isVue && isGenerated ? generated : vuesource
}
config.output.devtoolFallbackModuleFilenameTemplate =
'webpack:///[resource-path]?[hash]'
}
},
}

karma-coverage includes node_modules

I have a karma config which for my unit test and code-cov. My project dir looks like below
RootFOlder
-karma.config.js
-webpack.test.config.js
-src/
--test.ts
--components
---ButonComponent
----Buttoncomponent.spec.ts
And my karma.config is below
// 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: [
'src/test.ts',
'src/components/**/*.component.ts',
],
// list of files / patterns to exclude
exclude: [
'node_modules',
'./src/tsconfig.spec.json'
],
plugins: [
require('karma-jasmine'),
require("karma-coverage"),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-webpack'),
require('karma-sourcemap-loader'),
require('ts-loader')
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/components/**/*.ts': ['coverage'],
'src/components/**/*.component.ts': ['webpack', 'sourcemap'],
'src/test.ts': ['webpack', 'sourcemap'],
},
webpack: require('./webpack.test.config'),
coverageReporter: {
reporters: [
{ type: 'text', subdir: 'text' },
{ type: 'html', subdir: 'report-html' },
]
},
...
...
});
}
And my webpack.
module.exports = {
devtool: 'inline-source-map',
mode: 'development',
target: 'node',
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loaders: ['ts-loader', 'angular-router-loader', 'angular2-template-loader']
}
....
....
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'test')
}),
// Removes warnings regarding Critical dependency
new webpack.ContextReplacementPlugin(
/\#angular(\\|\/)core(\\|\/)f?esm5/, path.join(__dirname, './src')
)
],
node: {
console: false,
global: true,
process: true,
Buffer: false,
setImmediate: false
}
}
The problem is after i run my test, my coverage covers the bundled node_modules. The file coverage endup being hude running in MBytes and my coverage low. Pls how do i exclude the node_modules from my coverage? Any help is appreciated .
By default you shouldn't even need to mention node_modules in the exclude path. Try removing it and see if the coverage is corrected?
If not,
try adding this to the preprocessors:
'!node_modules/**/*.*': ['coverage']

karma-eslint preprocessor not working

I'm using karma-eslint plugin. It looks very easy to use but for some reason, I don't see any errors or warnings and my tests are running smoothly even though I put some eslint errors
here is my karma.config.js file:
module.exports = function (config) {
config.set({
browsers: [process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome'],
singleRun: true,
frameworks: ['mocha'],
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap'],
'src/**/*.jsx': ['coverage'],
'test/**/*.js': ['eslint'],
},
eslint: {
engine: {
configFile: './.eslintrc',
emitError: true,
emitWarning: true
}
},
reporters: ['progress', 'coverage'],
coverageReporter: {
/* coverage configurations */
},
webpack: {
/* some webpack configurations */
}
The violation I planted in the one of my test.js files - define a new variable but not using it (eslint rule: 'no-unused-vars')
Please let me know if any further information is needed and I'll edit the post accordingly.
Cheers!
Found another solution!
in my webpack configuration I've used the eslint-loader' forwebpack` as follows:
webpack: {
module: {
preLoaders: [
{test: /\.js$/, exclude: /(src|node_modules)/, loader: 'eslint-loader'}
]
}
}