Unable to run Coverage with Karma - javascript

I'm trying to run coverage with karma, and I get the warning: WARN [preprocess]: Can not load "coverage", it is not registered!
I thought I installed coverage when I ran 'npm install -g karma-coverage --save-dev'
Here's my config file:
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
bunch of files..
],
// list of files to exclude
exclude: [],
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress'
// CLI --reporters progress
reporters: ['progress', 'coverage'],
junitReporter: {
// will be resolved to basePath (in the same way as files/exclude patterns)
outputFile: 'test-results.xml'
},
// web server port
// CLI --port 9876
port: 9876,
// enable / disable colors in the output (reporters and logs)
// CLI --colors --no-colors
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
// CLI --log-level debug
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
// CLI --browsers Chrome,Firefox,Safari
browsers: ['ChromeCanary'],
// If browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// Auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: true,
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
// compile coffee scripts
preprocessors: {
'someFileName': ['coverage'],
},
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-firefox-launcher',
],
coverageReporter: {
'type' : 'cobertura',
'dir': 'coverage/'
}
});
};

I got the same [WARN] because the plugin 'karma-coverage' was not defined inside the plugins of the config, try to see if adding it fixes your warning, not sure if it will fix your full problem.
plugins: [
'karma-jasmine',
'karma-coverage',
'karma-chrome-launcher',
'karma-firefox-launcher',
],
UPDATE:
I also had a different problem when running the coverage, caused by istanbul, my error was
[coverage]: [TypeError: Cannot set property 'covered' of undefined]
After having a look what istanbul was doing it turned out that the paths to some of my js unit files were outdated in the preprocessors.
It was doing some of the coverage reports but it was not generating deep coverage reports for all files hence the error. Once I fixed the paths it was all good.
preprocessors : {
'**/app/js/*/*.js' : 'coverage',
'**/app/js/modules/*/*.js' : 'coverage',
'**/app/js/services/*/*.js' : 'coverage'
},

For what it's worth, this works fine for me. Installed with:
npm install -g karma
npm install -g karma-coverage
Config in karma.config.js:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: ['app.js','tests.js'],
preprocessors: { 'app.js': 'coverage' },
reporters: ['dots', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 60000,
singleRun: false
});
};
Run with karma start karma.config.js.

For those who are using grunt test to run the karma test, and have the problem of coverage plugin not loaded issue. Please add the plugins setting into your Gruntfiles.js karama task, i.e.
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true,
plugins:[
'karma-jasmine',
'karma-coverage',
'karma-phantomjs-launcher'
],
}
}

Solution with no global install
Install karma-coverage:
npm install --saved-dev karma-coverage
Then edit karma.conf.js and add require('karma-coverage') to the array of plugins.
module.exports = function (config) {
config.set({
// ...
plugins: [
require('karma-coverage'), // ADD THIS
// ...
],
});
}

I had the same issue, until I moved karma.conf.js into the same directory as package.json, then it worked.

This problem is described in this answer.
When using a globally installed karma it doesn't load the locally installed plugins. Using node_modules/.bin/karma to start the tests should solve this problem.
The installation of the coverage module in the global "namespace" also works but is probably not what you want.

I think the correct solution is
DON'T install karma globally
INSTALL karma-cli globally and install karma locally
npm i -g karma-cli
That's the problem then, you should use karma-cli globally, http://karma-runner.github.io/0.12/intro/installation.html
If you install karma globally it doesn't use the local installation.
reference: github

If you face this issue with Angular 13. Install karma-coverage and here's the full config:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('#angular-devkit/build-angular/plugins/karma'),
],
client: {
clearContext: false, // leave Jasmine Spec Runner output visible in browser
},
coverageReporter: {
dir: require('path').join(__dirname, './coverage/project-name'),
reporters: [
{
type: 'html',
},
{
type: 'lcov',
},
{
type: 'text-summary',
},
],
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome', 'ChromeHeadlessNoSandbox'],
singleRun: false,
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox'],
},
},
});
};

I installed karma-coverage globally it worked for me :-)
npm install -g karma-coverage

Related

Error after including plugins in karma.config.js

This is my code inside karma.config.js:
I'm using Webpack 3+ for my project.
module.exports = config => {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: ['./src/components/**/*.spec.ts'],
plugins: ['karma-jasmine', 'karma-phantomjs-launcher'],
preprocessors: {
'./src/components/**/*.spec.ts': ['webpack']
},
mime: {
'text/x-typescript': ['ts', 'tsx']
},
webpack: webpackConfig,
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
webpackMiddleware: {
noInfo: true
},
concurrency: Infinity
});
};
After I've included this line of code:
plugins: ['karma-jasmine', 'karma-phantomjs-launcher'],
I got the following error:
Can not load "webpack", it is not registered!
If I don't have this line, everything runs smoothly. The problem is I have to implement PhantomJS. How can I resolve the issue?
By default, Karma loads all sibling NPM modules which have a name starting with karma-*.
Looks like you are overriding plugins with a new array, which will stop any karma webpack plugins from being loaded.
Therefore, when specifying a new plugins array you should add karma-* to it:
plugins: ['karma-*', 'karma-jasmine', 'karma-phantomjs-launcher'],
However, as your plugins are karma- prefixed anyway, they should be loaded automatically with the default plugins config so you shouldn’t need to specify a plugins array in this case.
I hope this helps.

karma-webpack : Module name has not been loaded yet for context : use require([])

I'm new to Jasmine/Karma unit testing for JavaScript applications. I'm trying to implement it in my current project which is using Angular 1.4.12 and Webpack 1.13.1 for bundling. My folder structure is as follows:
The index.js file inside 'core' is trying to require various other modules which are required for Webpack bundling. The file looks like this:
require('../../bower_components/font-awesome/css/font-awesome.min.css');
require('../../bower_components/bootstrap/dist/css/bootstrap.min.css');
require('./scripts/app');
require('./scripts/index');
require('./views/index');
require('./styles/index');
Now, when I'm trying to run a sample test file which resides at the following location: 'modules/st/scripts/controllers/st.test.js', I get the following error message:
Uncaught Error: Module name
"../../bower_components/font-awesome/css/font-awesome.min.css" has not
been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded at
C:/gitcode/repo/fm-dashboard/node_modules/requirejs/require.js:143
My karma.conf.js file looks like:
var webpack = require('webpack');
var getWebpackConfig = require('./webpack.config.js');
var webpackConfig = getWebpackConfig('test');
webpackConfig.output.path = __dirname+'/_build/test';
webpackConfig.entry = {};
// 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: [
'./node_modules/requirejs/require.js',
'./app/core/index.js',
'./bower_components/angular/angular.js',
'./bower_components/angular-mocks/angular-mocks.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'../app/core/index.js': ['webpack']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
}
})
}
I was under the impression that including Webpack in the preprocessors object would resolve this require issue but seems like this is not the case.
I tried including 'commonjs' in my preprocessors object and frameworks array as suggested by a few people but it didn't help. Can anyone please let me know how to get rid of this 'require' issue and move ahead with my testing?
Thanks in advance.

Jasmine Test returns error "Uncaught ReferenceError: require is not defined"

First of all, I know this question has been asked other times, but it seems to be different.
This is my karma config file:
// Karma configuration
// Generated on Thu Jan 21 2016 09:58:23 GMT-0300 (Argentina Standard Time)
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/*.js',
'test/*.js',
'src/*.js',
'tests/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
This is my test so far in order to make it work:
require('../src/person.js');
describe('Person ', function(){
it('Should say hi with proposed first name and last name', function() {
var person = new person();
expect(true).toEqual(true);
});
});
When I run karma I'm getting the error saying require is not defined.
How ever, karma-requirejs is installed globally by npm.
I was reading this question that seems to be the same problem:
Jasmine Tests give error "Uncaught ReferenceError: require is not defined"
But after adding
plugins : [
'karma-requirejs',
],
to the karma conf file, I have a lot of other errors, that seems it does not recognize this attibute?
How can I fix the error?
I suggest installing karma-requirejs in your project's root, or where all of your other npm modules live local to the project.

Karma/systemjs not looking in node_modules directory when trying to run tests

I'm trying to run tests using karma/jasmine/systemjs with Angular 2 and typescript. I previously had it working without systemjs/typescript using babel.
I also got it working transpiling typescript to es6 and using the same karma setup without using systemjs.
I want to use systemjs, and I don't want to have to do transpile twice, so now I'm trying to use systemjs with karma. (using karma-system.js).
The error I'm getting is:
Error: XHR error (404 Not Found) loading /path/to/project/angular2/core.js
For whatever reason, karma/systemjs is not looking in the node_modules directory for angular, and I don't want to hard code that into my project files.
karma.conf.js:
module.exports = function(config) {
config.set({
basePath: '',
plugins: ['karma-systemjs', 'karma-jasmine', 'karma-chrome-launcher'],
frameworks: ['systemjs', 'jasmine'],
files: [
'client/**/*.spec.js',
'client/**/**/*.spec.js',
'server/**/*.spec.js',
'server/**/**/*.spec.js'
],
exclude: [
'node_modules/',
'client/node_modules/*',
'client/node_modules/**/*.spec.js',
'server/node_modules/*'
],
preprocessors: {},
systemjs: {
configFile: 'system.conf.js',
serveFiles: [
'client/**/*.js',
'server/**/*.js',
],
config: {
defaultJSExtensions: true
}
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: false,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
system.conf.js
System.config({
paths: {
'systemjs': 'node_modules/systemjs/dist/system.js',
'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js',
'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js'
}
});
In my typescript file, I'm loading angular core like this.
import { Component, View } from 'angular2/core';
and it gets transpiled to:
System.register(['angular2/core'], function(exports_1) {
I have tried adding a baseUrl to my systemjs config, it does not seem to do anything.
I have been "googling" and searching stack for a few hours now. I've looked at How to configure karma and systemjs to run tests for angular ES6 transpiled by traceur into amd format ES5 modules and Angular and ES6: Karma Testing with SystemJS and still have not fixed the issue.
in your system.conf.js file you should define a path for all angular modules like this:
System.config({
paths: {
'angular2/*': 'node_modules/angular2/bundles/*.js',
}
});

Karma doesn't find files specified in config file

I'm writing Jasmine tests to my Angularjs app.
I generated karma.conf.js using karma init but when I run karma start i get warnings like this:
WARN [web-server]: 404: /bower_components/angular/angular.js
WARN [web-server]: 404: /js/app.js
karma.conf.js is in my app folder, which is the place for the bower_components folder as well.
I think maybe that could be because of my local test server where I'm using this approach: https://github.com/mhevery/angular-node-socketio
(I've been able to set up the tests like this in other project without a test server)
Can anybody please point me in the right direction here?
Update:
My karma.conf.js looks like this:
module.exports = function(config) {
config.set({
basePath: '.',
frameworks: ['jasmine', 'requirejs'],
files: [
'tests/*.js',
'js/*.js',
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/d3/d3.js'
],
exclude: [],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 60000,
singleRun: false
});
};
Here's my directory structure:
Now that you've fixed the basepath (from '.' to '', see question comments above), you should change the order of files loading in your karma.conf.js :
module.exports = function(config) {
config.set({
basePath: '.',
frameworks: ['jasmine', 'requirejs'],
files: [
//load angular.js first
//(unless if you use jQuery which must be first if I remember well)
'bower_components/angular/angular.js',
//Then angular-modules
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-mocks/angular-mocks.js',
//Other libs
'bower_components/d3/d3.js',
//Your app scripts
'js/*.js',
//And your specs
'tests/*.js'
],
exclude: [],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 60000,
singleRun: false
});
};
You can find more info here: http://karma-runner.github.io/0.10/config/files.html
Ordering
The order of patterns determines the order of files in which they are included in the browser.
Multiple files matching a single pattern are sorted alphabetically.
Each file is included exactly once. If multiple patterns match the same file, it's included as if it only matched the first pattern.
Your problem is probably the order you're loading your files in.
You may need to change the order to something like:
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/d3/d3.js',
'js/*.js',
'tests/*.js'
],

Categories