I am writing unit tests for angularjs application using karma Jasmine. When i am trying to run command karma start it throws an error like Uncaught ReferenceError: define is not defined. Basically i am trying to load a separate module(whose file starts with a define keyword.) which has a dependency in my application module using karma config file, in files section.
I have no idea why this is happening and any help would be greatly appreciated.
I had similar problem and it wasn't so easy to find the solution.
Next time provide some code, in this case your Karma and Jasmine configuration files because they are responsible for this kind of problems.
You probably haven't used or haven't configured RequireJS for Karma.
This link should be helpful.
Karma - RequireJS documentation
Just write 'karma init' in console, choose "yes" for Require.js. More details in link.
Very important is to have correct folder structure and play where you have your karma.conf.js and test-main.js(RequireJS config file).
The example structure that I decide to use after hours of research and trials and errors.
.
- karma
├── karma.conf.js
├── build
| ├── js
| └── tests
| ├── test-main.js
| ├── tes
karma.conf.js
// Karma configuration
// Generated on Fri Mar 16 2018 09:14:49 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'build/tests/test-main.js',
{pattern: 'build/**/*.js', included: false},
{pattern: 'documents/exampleData/**/*.js', included: false},
{pattern: 'node_modules/**/*-min.js', included: false},
{pattern: 'node_modules/d3/build/d3.js', included: false},
{pattern: 'node_modules/jquery/dist/jquery.min.js', included: false},
{pattern: 'build/tests/**/*.js', included: false},
],
// list of files / patterns 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
})
}
test-main.js
var tests = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var BASE_URL = '/base/build/js';
var BASE_URL_REGEXP = /^\/base\/build\/js\/|\.js$/g;
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function (file) {
if (TEST_REGEXP.test(file)) {
var normalizedTestModule = file.replace(BASE_URL_REGEXP, '')
tests.push(normalizedTestModule)
}
})
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: BASE_URL,
paths: {
'env': 'env',
'Utils': './utils/utils',
'exampledata' : '../../documents/exampleData',
'jquery': '../../node_modules/jquery/dist/jquery.min',
'underscore': '../../node_modules/underscore/underscore-min',
'backbone': '../../node_modules/backbone/backbone-min',
'backbone.touch': '../../node_modules/backbone.touch/dist/backbone.touch.min',
'd3' : '../../node_modules/d3/build/d3'
},
shim: {
'underscore': {
exports: '_'
}
},
deps: tests,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
})
This solution for now maybe isn't perfect but it works. I will be very satisfied if I will find something like that at the beginning of research.
I will update it when I get a little bit familiar with best practices of test frameworks configuration.
Related
Hello all I am trying to do some jasmine/karma testing on a d3 application however I cannot get past this error: ReferenceError: Can't find variable: d3...
at getSvg (C:/Users/test/Desktop/bob/angular-force-directed-graph/src/app/d3mapping.spec.js:9)
at C:/Users/test/Desktop/bob/angular-force-directed-graph/src/app/d3mapping.spec.js:9
ReferenceError: Can't find variable: d3
I know it has something to do with d3 being undefined until window.load but I am not sure how to properly define d3 and the methods it uses.
// Karma configuration
// Generated on Thu Oct 29 2015 14:09:24 GMT-0400 (Eastern Daylight Time)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: 'app',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',
'bower_components/d3/d3.js',
'home/*.js',
'common/*.js',
'home/home.module.js',
'app.js',
'**/*.module.js',
'**/*.controller.js',
'**/*.service.js',
'**/*.directive.js',
'**/*.routes.js',
'**/*.spec.js'
],
// list of files to exclude
exclude: [
'bower_components/**/!(angular*|angular-mocks|angular-route*).js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'!(bower_components)/**/!(*spec).js': 'coverage',
'*.js': 'coverage'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
coverageReporter: {
dir: '../coverage/',
subdir: 'report'
},
captureTimeout: 30000,
// 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: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome', 'Firefox', 'IE', 'PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity
})
};
add d3 to your karma.conf.js files
if your project structure looks like this
|--app
| |--app.js
| |--...
|
|--test
| |--karma.conf.js
|
|--bower_components
you have to set the basePath to '../' because the karma.conf.js file lies inside the test folder but you want to address the files via 'app/app.js' or 'bower_components/...'
config.set({
basePath: '../' // dont forget the right basePath!
files:[
'path/to/d3'
],
...
})
This is my karma/karma.conf.js:
// Karma configuration
// Generated on Mon Jan 04 2016 16:17:18 GMT-0500 (EST)
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: [
],
// 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: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
and this is my karma/tests/test_post.js:
describe('Controller: MainCtrl', function() {
beforeEach(module('PostPageApp'));
var ctrl;
beforeEach(inject(function($controller) {
ctrl = $controller('MainCtrl');
}));
it('Show have an add and logout function', function() {
expect(ctrl.add).toBeDefined();
});
});
and this is ../post.js:
angular.module("PostPageApp", ["BaseApp"])
.controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
var self = this;
self.add = function() {
BaseService.add.post(self.post, function() {
self.cerrorMessages = BaseService.cerrorMessages;
});
};
self.logoutUser = function() {
BaseService.logout();
};
}]);
Now, when I do karma start, it returns this:
04 01 2016 16:48:10.137:INFO [karma]: Karma v0.13.17 server started at http://localhost:9876/
04 01 2016 16:48:10.144:INFO [launcher]: Starting browser Chrome
04 01 2016 16:48:13.138:INFO [Chromium 47.0.2526 (Ubuntu 0.0.0)]: Connected on socket ayhU7qR23sshUzi3AAAA with id 50222765
Chromium 47.0.2526 (Ubuntu 0.0.0): Executed 0 of 0 ERROR (0.013 secs / 0 secs)
Any idea why it is executing 0 out of 0 and returning an error? I thought it would run
it('Show have an add and logout function', function() {
expect(ctrl.add).toBeDefined();
});
Please note that I am new to using Karma and Jasmine so I am still trying to get the hang of all of this.
Thanks in advance.
It's not running any tests because you aren't telling it to load any files into the browser. I think a lot of people use RequireJS for this, but unfortunately I am not familiar with it.
In karma.conf.js under the files: section:
List your JS dependencies (like JQuery or Angular).
List the files that you are testing next.
List the test specs themselves last.
For instance:
files: [
'angular.js',
'app.js',
'app.spec.js'
]
If you don't want certain files to be included then put them in the exclude section. Make sure the file paths are relative to where karma.conf.js is located.
I would suggest specifying a default path and a pattern at ./karma.conf.js:
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: 'test/',
// list of files / patterns to load in the browser
files: [
{pattern: '**/*.js*', included: true}
],
It worked for me.
I have an Angularjs project and I am using karma to run the tests. I am running into some problems with it, getting this error:
ReferenceError: Can't find variable: require
at http://localhost:9876/base/src/test/bower_components/angular-animate/index.js?b8fe1c0a06b723a75c7e596fd8a86d91965f681c:1
Reding into some forums, I was told to use karma browserify, but I am getting this error now:
28 07 2015 22:41:15.573:WARN [preprocess]: Can not load "browserify", it is not registered!
Perhaps you are missing some plugin?
/Users/brunosiqueira/WebstormProjects/copcast-admin/node_modules/karma/node_modules/di/lib/injector.js:9
throw error('No provider for "' + name + '"!');
^
Error: No provider for "framework:browserify"! (Resolving: framework:browserify)
at error (/Users/brunosiqueira/WebstormProjects/copcast-admin/node_modules/karma/node_modules/di/lib/injector.js:22:68)
at Object.parent.get (/Users/brunosiqueira/WebstormProjects/copcast-admin/node_modules/karma/node_modules/di/lib/injector.js:9:13)
at get (/Users/brunosiqueira/WebstormProjects/copcast-admin/node_modules/karma/node_modules/di/lib/injector.js:54:19)
at /Users/brunosiqueira/WebstormProjects/copcast-admin/node_modules/karma/lib/server.js:128:20
at Array.forEach (native)
at Server._start (/Users/brunosiqueira/WebstormProjects/copcast-admin/node_modules/karma/lib/server.js:127:21)
at invoke (/Users/brunosiqueira/WebstormProjects/copcast-admin/node_modules/karma/node_modules/di/lib/injector.js:75:15)
at Server.start (/Users/brunosiqueira/WebstormProjects/copcast-admin/node_modules/karma/lib/server.js:92:18)
at Function.Server.start (/Users/brunosiqueira/WebstormProjects/copcast-admin/node_modules/karma/lib/server.js:101:10)
at Object.<anonymous> (/Applications/WebStorm.app/Contents/plugins/js-karma/js_reporter/karma-intellij/lib/intellijServer.js:10:8)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
Does anybody know what's going on? This is my karma.conf file:
{
// Karma configuration
// Generated on Tue May 19 2015 15:02:17 GMT+0100 (WEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
plugins: [
'karma-browserify',
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor',
'karma-spec-reporter'
],
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: [ 'browserify','jasmine'],
// list of files / patterns to load in the browser
files: [
'http://maps.googleapis.com/maps/api/js?sensor=false&language=en',
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'bower_components/bootstrap-select/dist/js/bootstrap-select.js',
'bower_components/angular/angular.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-ui-utils/ui-utils.js',
'bower_components/angular-ui-map/ui-map.js',
'bower_components/angular-http-auth/src/http-auth-interceptor.js',
'bower_components/ng-file-upload/ng-file-upload.js',
'bower_components/ng-file-upload-shim/ng-file-upload-shim.js',
'bower_components/angular-notify/dist/angular-notify.js',
'bower_components/moment/moment.js',
'bower_components/angular-gettext/dist/angular-gettext.js',
// endbower
'src/app/**/*.js',
'src/app/views/**/*.html',
'src/test/**/*.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'**/*.html': ['ng-html2js'],
'**/*.js': [ 'browserify' ]
},
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'src/',
// prepend this to the
// setting this option will create only a single module that contains templates
// from all the files, so you can load them all with module('foo')
moduleName: 'templatesForTest'
},
// test results reporter to use
// possible values: 'dots', 'progress', 'spec'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['spec'],
// 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: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
}
I had a similar problem:
Warning: No provider for "framework:mocha"! (Resolving: framework:mocha)
This happened because I didn't include the plugin. Correct config:
...
singleRun: true,
plugins: ['karma-phantomjs-launcher', 'karma-mocha'], // here
frameworks: ['mocha'],
...
Also worth mentioning, you'll need to install the plugin:
npm install karma-mocha --save-dev
https://www.npmjs.com/package/karma-mocha
After further experimentation, looks like this is the error message delivered when you haven't included the plugin for a specified framework:
...
plugins: ['karma-phantomjs-launcher', 'karma-mocha', 'karma-chai'],
frameworks: ['mocha', 'chai'], // Will require the plugins above
...
I had a few problems with different versions of the libraries. But in the end, I got to make to work like this:
My package.json file:
"karma": "0.12.0",
"karma-html2js-preprocessor": "0.1.0",
"karma-jade-preprocessor": "0.0.11",
"karma-jasmine": "0.1.5",
"karma-ng-html2js-preprocessor": "0.1.2",
"karma-phantomjs-launcher": "0.1.4",
"karma-requirejs": "0.2.1",
"karma-script-launcher": "0.1.0",
"karma-coffee-preprocessor": "0.2.1",
"brfs": "^1.2.0",
"browserify-shim": "~3.8.0",
"karma-browserify": "^3.0.0",
My karma.conf.js file:
// Karma configuration
// Generated on Tue May 19 2015 15:02:17 GMT+0100 (WEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: [ 'jasmine', 'browserify'],
// list of files / patterns to load in the browser
files: [
'http://maps.googleapis.com/maps/api/js?sensor=false&language=en',
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'bower_components/bootstrap-select/dist/js/bootstrap-select.js',
'bower_components/angular/angular.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-ui-utils/ui-utils.js',
'bower_components/angular-ui-map/ui-map.js',
'bower_components/angular-http-auth/src/http-auth-interceptor.js',
'bower_components/ng-file-upload/ng-file-upload.js',
'bower_components/ng-file-upload-shim/ng-file-upload-shim.js',
'bower_components/angular-notify/dist/angular-notify.js',
'bower_components/moment/moment.js',
'bower_components/angular-gettext/dist/angular-gettext.js',
// endbower
'src/app/**/*.js',
'src/app/views/**/*.html',
'src/test/**/*.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'**/*.html': ['ng-html2js'],
'src/**/*.js': ['browserify']
},
browserify: {
debug: true,
transform: [ 'brfs' ]
},
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'src/',
// prepend this to the
// setting this option will create only a single module that contains templates
// from all the files, so you can load them all with module('foo')
moduleName: 'templatesForTest'
},
// test results reporter to use
// possible values: 'dots', 'progress', 'spec'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['spec'],
// 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: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
UPDATE
I recently updated all my libraries to the most recent version and I got this error again. I realized that I was missing the library browserify and watchify themselves. So I installed the two missing libraries and everything worked perfectly.
npm install --save-dev karma-browserify browserify watchify
In my javascript, document.getElementById always returns null in just case of run in karma. It's no problem when I load the html directly drop on browser. I think karma configuration is something wrong.
// Karma configuration
// Generated on Sun Jul 26 2015 14:08:25 GMT+0900 (JST)
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: ['mocha'],
// list of files / patterns to load in the browser
files: [
'listtest.html',
{pattern: 'js/*.js', included: false},
{pattern: 'test/*.js', included: false}
],
// 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
})
}
What is my mistake?
I find that karma could not include html files as default. To load html, html2js preprocessor is necessary. After convert html to js, karma can assign html to document object, but I don't know how to do that.
I ma trying to add Karma & Jasmine+Require Js based Unit testing support for an AngularJS +Angular AMD & RequireJS Application that I have created. I have been wrecking my brain around this for two days now but I am still nowhere close to sealing the deal.
I keep getting the error :
INFO [karma]: Karma v0.12.21 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 36.0.1985 (Mac OS X 10.9.4)]: Connected on socket 8oFHaa2hqJPs0ecgIXCa with id 31963369
Chrome 36.0.1985 (Mac OS X 10.9.4) ERROR: 'There is no timestamp for ../www/scripts/specs/UserControllerTest.js!'
WARN [web-server]: 404: /www/scripts/specs/UserControllerTest.js
Chrome 36.0.1985 (Mac OS X 10.9.4) ERROR
Uncaught Error: Script error for: specs/UserControllerTest
http://requirejs.org/docs/errors.html#scripterror
at /usr/local/lib/node_modules/requirejs/require.js:141
My Code is as follows :
The Karma Config file :
// Karma configuration
// Generated on Fri Aug 15 2014 20:49:40 GMT+1000 (EST)
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', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'test-main.js',
{pattern: 'specs/*.js', included: true}
],
// 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
});
};
My test-main.js file.
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '../www/scripts',
// alias libraries paths
paths: {
'angular': '../libs/angular',
'angular-route': '../libs/angular-route',
'angular-animate':'../libs/angular-animate',
'angular-mocks':'../libs/angular-mocks',
'angularAMD': '../libs/angularAMD.min',
'Framework7':'../libs/framework7',
'UserController':'controller/UserCtrl',
'WebCallManager':'services/WebCallManager'
},
// Add angular modules that does not support AMD out of the box, put it in a shim
shim: {
'angularAMD': ['angular'],
'angular-route': ['angular'],
'angular-animate':['angular'],
'angular-mocks':['angular'],
'Framework7':{exports: 'Framework7'}
},
//kick start application
//deps: ['app'],
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
And My Unit Test is :
describe('UserController', function () {
var scope,controller;
//mock Application to allow us to inject our own dependencies
beforeEach(angular.mock.module('app'));
//mock the controller for the same reason and include $rootScope and $controller
beforeEach(angular.mock.inject(function($rootScope, $controller) {
//create an empty scope
scope = $rootScope.$new();
//declare the controller and inject our empty scope
$controller('UserController', {$scope: scope});
}));
it('checks the controller name', function () {
expect(scope.name).toBe('Superhero');
});
});
I have uploaded all my code of my project to link here. Anyone who can help me with this is highly appreciated. I think In am at the end of my tether with this.
marcoseu is right, the There is no timestamp for... error means karma cant find the the file, but there is more.
I'd recommend making karma's base path your project root. This avoids Karma making the file paths absolute instead of relative which keeps things simpler and avoids path reference problems (at least on my windows OS).
Your test should be a require module (i.e. using define) so it can be sure the objects it requires are fully loaded. See the example test at http://karma-runner.github.io/0.12/plus/requirejs.html
karma.config.js
basePath: "../",
files: [
'test/test-main.js',
{pattern: 'test/specs/*.js', included: false},
{pattern: 'www/**/*.js', included: false},
],
Now your files are all served by Karma under /base.
test-main.js
require.config({
baseUrl: "/base/www/scripts",
Debugging
But most importantly you can debug all of this. Run Karma, switch to the Karma created chrome instance, click the debug button, open the chrome developer tools. Check the console, and your source files. Especially the source of debug.html, as at the bottom it has the definition of all your karma served files.
You can also set breakpoints and then refresh the page to watch the tests being executed. You will be able to see for yourself why you are getting test errors. Win.
The error There is no timestamp for... means that karma is unable to access the file in question. You need to define the www directory so that is is accessible by karma. Try the following:
karma.config.js
files: [
'test-main.js',
{pattern: './specs/*.js', included: true},
{pattern: '../../www/**/*.js', included: false}
],
Take a look at karma.conf in the angularAMD project and the Karma documentation for files.