Karma doesn't find files specified in config file - javascript

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'
],

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.

Karma: Is it possible to load JavaScript files statically before the requirejs framework?

I'm wondering if it's possible to configure Karma (0.10.9) to load certain JavaScript files before its requirejs framework? The reason I'm asking is that Knockout registers as a module with RequireJS if the latter has been included before Knockout, and this breaks another module (which doesn't support RequireJS).
Basically, our karma.conf.js looks as below:
module.exports = function (config) {
config.set({
basePath: "Scripts",
frameworks: ['mocha', 'requirejs'],
files: [
"knockout-2.2.1.debug.js",
"knockout.viewmodel.2.0.3.js",
{pattern: "test/**/*.js", included: false},
{pattern: "shared/**/*.js", included: false},
{pattern: "app/**/*.js", included: false},
],
reporters: ['progress', 'growl'],
// web server port
// CLI --port 9876
port: 9876,
// cli runner port
// CLI --runner-port 9100
runnerPort: 9100,
autoWatch: true,
browsers: ["PhantomJS"],
// If browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 5000,
// Auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: false,
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
plugins: [
'karma-mocha',
'karma-phantomjs-launcher',
'karma-growl-reporter',
'karma-requirejs'
]
});
}
Apparently it can be done by manually including karma-requirejs files and not including it among the frameworks:
frameworks: ['mocha'],
files: [
"knockout-2.2.1.debug.js",
"knockout.viewmodel.2.0.3.js",
'node_modules/requirejs/require.js',
'node_modules/karma-requirejs/lib/adapter.js',
{pattern: "test/**/*.js", included: false},
{pattern: "shared/**/*.js", included: false},
{pattern: "app/**/*.js", included: false}
]
See this Karma issue for reference.

Batmanjs testing on Rails with Karma

I'd like to use batmanjs karma and rails on a current project. At the moment I'm attempting to use the batmanjs testing framework, but I'm having a heck of time getting everything to play together. Any help would be appreciateed.
http://batmanjs.org/docs/testing.html
class SimpleTest extends Batman.TestCase
#test 'A simple test', ->
#assert true
This file is sitting in spec/javascripts/simple_spec.js.coffee
Here's my Karma config, I'm assuming it's not accurate.
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['requirejs'],
files: [QUNIT, QUNIT_ADAPTER,
{pattern: 'spec/javascripts/*.js.coffee', included: false}
],
exclude: [
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome', 'PhantomJS'],
captureTimeout: 60000,
singleRun: false
});
};
Again, any help would be appreciated.
Somehow you need to get Batman.TestCase (and your application code) loaded by Karma. What I've done before is (gulp) point Karma at my development server, where it can get compiled assets. Maybe it ain't perfect, but it works.
Here's an example snippet for your Karma config:
files: [
'spec/javascripts/**/*.coffee',
'http://localhost:3000/assets/your_app.js', // loads application code
'http://localhost:3000/assets/extras/batman.test_case.js' // point to wherever TestCase code is!
]
Also,I wrote up a bit about how I've done it before (with Jasmine), in case that comes in handy: http://rmosolgo.github.io/blog/2014/01/18/batman-dot-js-testing-with-karma-and-jasmine/
As mentioned there, Batman.TestCase is an "extra", so you'll have to include it "by hand". It's not in the distributed version of Batman.js
Does that help at all? Good luck!

Unable to run Coverage with Karma

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

Categories