I've created a simple test application that write hello.
The application is:
boot.js
require.config({
appDir: '',
baseUrl: '',
paths: {
angular: 'app/bower_components/angular/angular',
Controller: 'app/js/Controller'
},
shim: {
'angular': {'exports': 'angular'}
},
config: {
},
priority: [
"angular"
]
});
require(['app/js/Module'], function()
{
console.log("Loaded!");
});
Module.js:
(function(define) {
"use strict";
define(['angular', 'Controller'],
function(angular, NccController) {
var app, appName = 'myApp';
app = angular
.module(appName, [])
.controller('Controller', NccController);
angular.bootstrap(document.getElementsByTagName("body")[0], [appName]);
return app;
});
}(define));
Controller.js
(function(define) {
"use strict";
define([], function()
{
var NccController = function($scope)
{
$scope.message = "ciao"; //data to graph
};
return NccController;
});
}(define));
The content of karma.conf.js is:
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: [
{pattern: 'public_html/app/bower_components/angular/angular.js', included: false}
'test-main.js',
{pattern: 'public_html/app/js/*.js', included: false},
{pattern: 'public_html/app/test/**/*Spec.js', included: false},
],
// list of files to exclude
exclude: [
'public_html/app/js/boot.js'
],
// 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
});
};
the test-main.js is
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: '/base',
paths: {
'angular': 'public_html/app/bower_components/angular/angular',
'Module': 'public_html/app/js/Module',
'Controller': 'public_html/app/js/Controller',
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
the MainSpec.js is:
define(['Module','Controller'], function(angular,Module,Controller) {
describe('Controller', function(){
beforeEach(module('myApp'));
it('should print hello', inject(function($controller) {
var scope = {},
ctrl = $controller('Controller', {$scope:scope});
expect(scope.message).toBe('ciao');
}));
});
});
But when i run the test i obtain:
/usr/local/lib/node_modules/karma/bin/karma start
INFO [karma]: Karma v0.12.17 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 36.0.1985 (Mac OS X 10.8.5)]: Connected on socket 14waTQA-kAa0VgYpvBBk with id 39770086
Chrome 36.0.1985 (Mac OS X 10.8.5) ERROR
Uncaught TypeError: Cannot read property 'module' of undefined
at /Users/daniele/Desktop/JARK/public_html/app/js/Module.js:8
What's wrong????
Thank you a lot.
Great tbranyen,
you've solved my great problem after 2 days of configuration. I post here all codes because I think that there're a lot of people that want to use angular/karma/RequireJs but have a lot of difficulty to setup all.
So boot.js, Module.js and controller.js are the same otherwise the file:
karma.conf.js is:
// Karma configuration
// Generated on Sat Jul 26 2014 18:36:34 GMT+0200 (CEST)
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: [
{pattern: 'public_html/app/bower_components/angular/angular.js', included: false},
{pattern: 'public_html/app/bower_components/angular-mocks/angular-mocks.js', included: false},
{pattern: 'public_html/app/js/*.js', included: false},
{pattern: 'public_html/app/test/**/*Spec.js', included: false},
'test-main.js',
],
// list of files to exclude
exclude: [
'public_html/app/js/boot.js'
],
// 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
});
};
test.main.js is:
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: window.__karma__ ? "/base/" : "/",
paths: {
'angular': 'public_html/app/bower_components/angular/angular',
'angular-mocks': 'public_html/app/bower_components/angular-mocks/angular-mocks',
'Module': 'public_html/app/js/Module',
'Controller': 'public_html/app/js/Controller',
},
shim: {
'angular': {'exports': 'angular'},
'angular-mocks': ['angular']
},
});
require(['angular-mocks'], function() {
require(allTestFiles, window.__karma__.start);
});
and MainSpec.js is:
define(['angular','angular-mocks','Module','Controller'], function(angular,mocks,Module,Controller) {
describe('Controller', function(){
beforeEach(module('myApp'));
it('should print hello', inject(function($controller) {
var scope = {},
ctrl = $controller('Controller', {$scope:scope});
expect(scope.message).toBe('ciao');
}));
});
});
I hope that can help same people that want use it
Karma serves files under the /base/ root path, not /. You need to change your baseUrl property within the RequireJS configuration to be baseUrl: "/base/".
A simple way of handling this conditionally is:
baseUrl: window.__karma__ ? "/base/" : "/"
Edit:
I'm incorrect with the above, you have it configured correctly. The only other guess I have is that deps is loading your tests before the configuration has finished being set. Although you have mentioned that Angular loads 200 OK. My recommendation here would be to try extracting the test loading away from deps and instead break the configuration and loading into two different operations.
require.config({
"paths": { "angular": "<path/to/angular>" }
});
require(allTestFiles, function() {
window.__karma__.start();
});
I would also remove the callback from the karma Require configuration.
Edit 2:
Another recommendation would be to share your main application configuration so that you don't have to declare paths over again. An example of how this would look is:
https://gist.github.com/tbranyen/e37a7d888f7f90c25e63#file-config-js-L27-L28
Edit 3 (Hopefully last):
After debugging the project the error ended up being a missing Angular shim configuration in the test-main.js file.
Look at this project that uses requirejs and karma for angular js. Try and follow the set up. https://github.com/adikari/angular-seed
Related
I am configuring my Karma amd mocha framework with grunt in my project.
When I am running karma start I am getting below mentioned error.
Uncaught Error: [$injector:modulerr] Failed to instantiate module myModule due to: Error: [$injector:nomod] Module 'myModule' is not available!
My controller:
(function () {
var module = angular.module('myModule',[]);
module.controller('myCtrl', function($scope, $q, $rootScope, templateValuesSrv) {
function() {
var self = this;
self.firstName = '';
self.lastName = '';
self.getFullName = function() {
return self.firstName + ' ' + self.lastName;
};
return self;
}
});
})();
My Controller Spec:
describe('myCtrl', function() {
beforeEach(module('myModule'));
describe('getFullName()', function() {
it('should handle names correctly', inject(function($controller) {
var myController = $controller('myCtrl');
myController.firstName = 'George';
myController.lastName = 'Harrison';
myController.getFullName().should.equal('George Harrison');
}));
});
});
My Karma.conf.js
// Karma configuration
// Generated on Fri Nov 27 2015 11:48:47 GMT+0530 (India 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: ['mocha', 'chai'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'test/specs/*.js',
//'test/*.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: ['PhantomJS', 'Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity
})
}
Please suggest what I am missing.
Before the specs you should add the js files that you want to test.
// Karma conf
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/**/*.js',
'test/specs/*.js',
//'test/*.js'
],
If you use a bundler like webpackt or bower then you could require then on each spec
At the moment, I'm trying to setup a demo project with Node/AngularJs/JSPM with ES6 transpiler Babel and Karma.
The serving part is working. I need to improve it later but the first 'hello world' from angular is working.
I'd like to add Karma to run unit tests for the angular app. But I'm getting a 404 warning for jspm_packages, see screenshot below.
My test is not running because it will always fail. My test file looks like this (no angular specific part in there yet):
// HomeController.spec.js
import 'angular-mocks';
describe('Test suite for HomeController', function() {
it('dummy test', function() {
expect(true).toBe(true); // will not fail
});
});
Not sure what's wrong and I've tried many things with-out success maybe I did something wrong. But here is what I've tried in the Karma config:
Tried many different path setting because I think it's an issue with the path
Used proxies
Browserify and Bablify to transpile the sources
JSPM plugin to load the dependencies for testing
You can find the code I'm currently working on here at bitbucket.
The directory structure of my app looks like this:
Here is a screenshot of Karma:
Here is my current Karma config file:
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: ['jspm', 'jasmine'],
// list of files / patterns to load in the browser
files: [
//'client/test-unit/**/*.test.js'
],
jspm: {
paths: {
// '*': 'client/app/**/*.js'
},
// Edit this to your needs
// config: 'client/app/jspm.config.js',
// Edit this to your needs
loadFiles: ['client/test-unit/**/*.spec.js'],
serveFiles: ['client/app/**/*.js', 'client/app/**/*.css', 'client/app/**/*.html']
},
proxies: {
// '/assets/jspm_packages/': '/client/app/assets/jspm_packages/'
},
plugins:[
'karma-jasmine',
'karma-coverage',
'karma-jspm',
'karma-chrome-launcher'
],
// 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: {
// 'client/app/**/*.js': ['browserify'],
// 'client/test-unit/**/*.js': ['browserify']
},
/*browserify: {
debug: true,
transform: [ 'babelify' ]
},*/
// babelPreprocessor: {
// options: {
// sourceMap: 'inline'
// },
// filename: function (file) {
// return file.originalPath.replace(/\.js$/, '.es5.js');
// },
// sourceFileName: function (file) {
// return file.originalPath;
// }
// },
// 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
});
};
I think I've found a fix to my problem.
I had to setup some proxies to make it work.
Also the change of the log level to logLevel: config.LOG_DEBUG for debugging my issue was helpful because then you'll see more details to the problem.
Another problem was that the test file was not transpiled before execution. That was because the preprocessors for transpiling were not setup correctly.
And the packages path inside of the jspm object is required too to make it work.
It's still pretty hard to understand and I'm not sure if there's an easier way to do it.
Anyway the following karma.config is working for me:
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: ['jspm', 'jasmine'],
// list of files / patterns to load in the browser
files: [
//'client/test-unit/**/*.test.js'
],
proxies: {
'/base/app/': '/base/client/app/',
'/base/assets/jspm_packages/': '/base/client/app/assets/jspm_packages/'
},
jspm: {
// Edit this to your needs
config: 'client/app/jspm.config.js',
// Edit this to your needs
loadFiles: ['client/test-unit/**/*.spec.js'],
serveFiles: ['client/app/**/*.js'],
packages: "client/app/assets/jspm_packages/"
},
plugins:[
'karma-jasmine',
'karma-coverage',
'karma-jspm',
'karma-chrome-launcher'
],
// 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-unit/**/*.js': ['babel', 'coverage']
// 'client/app/**/*.js': ['browserify'],
// 'client/test-unit/**/*.js': ['browserify']
},
/*browserify: {
debug: true,
transform: [ 'babelify' ]
},*/
// babelPreprocessor: {
// options: {
// sourceMap: 'inline'
// },
// filename: function (file) {
// return file.originalPath.replace(/\.js$/, '.es5.js');
// },
// sourceFileName: function (file) {
// return file.originalPath;
// }
// },
// 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_DEBUG, //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
});
};
And my test file looks like this:
// HomeController.spec.js
import 'app/app';
import 'angular-mocks';
describe('Test suite for HomeController', function() {
// var homeController;
beforeEach(function() {
module('myApp');
// inject(function($controller) {
// console.log('inject called', $controller);
// //controller = $controller;
// homeController = $controller('homeController');
// });
});
it('should say "Hello World"', inject(function($controller) {
var homeController = $controller('homeController');
// console.log(homeController, angular.mocks);
expect(homeController.hello).toEqual('Hello world from ES6 HomeController.'); // will not fail
})
);
});
I have a project that is using angularjs with requirejs and testing with karma. I am having trying with testing a service in the project.
These are my files that I have configured with angularjs, requirejs, and karma. When I run my service test I get this error TypeError: Cannot read property 'inject' of undefined. If I comment out the beforeEach part in the test code everything runs fine, but I can't do that in the real tests.
test-main.js
var allTestFiles = [], file;
for (file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if(/test\.js$/.test(file)) {
allTestFiles.push(file);
}
}
}
require.config({
baseUrl: '/base',
// alias library paths
// must set 'angular'
paths: {
'jquery': 'web/common/js/vendor/jquery-1.10.2/jquery-1.10.2.min',
/* common includes */
'angular' : 'web/common/js/vendor/angular/angular',
'angular-ui-router' : 'web/common/js/vendor/angular/angular-ui-router.min',
'angular-css-injector' : 'web/common/js/vendor/angular/angular-css-injector',
'angular-animate' : 'web/common/js/vendor/angular/angular-animate.min',
'angularAMD' : 'web/common/js/vendor/angular/angularAMD',
'ssss-abs-tpls' : 'web/common/js/sandbox/ssss-abs-tpls',
'angular-sanitize' : 'web/common/js/sandbox/angular-sanitize',
'modernizr' : 'web/common/js/vendor/modernizr/modernizr',
'scrollToPlugin' : 'web/common/js/vendor/ScrollToPlugin/ScrollToPlugin',
'TweenMax' : 'web/common/js/vendor/TweenMax/TweenMax',
'gestures' : 'web/common/js/vendor/gestures/gestures',
'ssss-base' : 'web/common/js/framework/ssss.base',
'hammer' : 'web/common/js/framework/hammer',
'angular-mocks' : 'web/common/js/vendor/angular/angular-mocks',
/* controllers,not listed*/
/* services */
'MyService' : 'app/services/models/MyService',
/* directives, not listed*/
/* router */
'MyApp' : 'app/MyApp',
/*utils*/
'Message' : 'app/utils/message'
},
/* For angular modules that do not support AMD out of the box, specify them in shim */
shim: {
'angular-ui-router' : ['angular'],
'gestures': ['angular'],
'angular-sanitize': ['angular'],
'angular-css-injector': ['angular'],
'angular-animate': ['angular'],
'ssss-session': ['angular'],
'ssss-abs-tpls' : ['angular','gestures','angular-sanitize'],
'angular-mocks' : ['angular']
},
/* kick start the application */
//deps: ['eMaintenance'],
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
karma.conf.js
// Karma configuration
// Generated on Wed Nov 05 2014 15:22:19 GMT-0600 (Central 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', 'requirejs'],
// list of files / patterns to load in the browser
files: [
{pattern: 'web/common/*.js', included: false},
{pattern: 'web/common/**/*.js', included: false},
{pattern: 'app/*.js', included: false},
{pattern: 'app/**/*.js', included: false},
{pattern: 'test/*.js', included:false},
{pattern: 'test/**/*.js', included:false},
{pattern: 'test-main.js', included: true}
],
// list of files to exclude
exclude: [
/*requirejs paths file*/
'app/main.js'
],
// 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,
plugins:[
'karma-requirejs',
'karma-chrome-launcher',
'karma-jasmine',
'karma-phantomjs-launcher'
]
});
};
MyService.js
define(['myApp'], function (app) {
app.register.factory("MyService",["$http","$q", function($http, $q) {
getData:function(){
var data = {
"test1":"some data"
};
return {
then:function(myFunc){
myFunc(data);
}
};
}
};
}]);
});
MyService.test.js
define(['angular-mocks','MyApp','MyService'],
function (mocks, app, MyService) {
describe('MyService test', function(){
var service;
beforeEach(mocks.inject(function(MyService){
service = MyService;
}));
it('should do something', function(){
expect('abc').toBe('abc');
});
});
});
Just call inject not mocks.inject ! It should works now !
beforeEach(inject(function(MyService){
service = MyService;
}));
I'm currently attempting to run tests using Karma, however I can't seem to load the Test file...
this is my file structure:
app
controllers
..
directives
..
..
test
customersControllerTest.js
karma.conf.js
test-main.js
..
this is my current karma.conf.js file:
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: [
{pattern: './scripts/jquery.js', included: true},
{pattern: './scripts/angular.js', included: true},
{pattern: './scripts/angular-mocks.js', included: true},
'test-main.js',
{pattern: './test/*.js', included: false},
{pattern: './app/**/*.js', included: false},
],
// list of files to exclude
exclude: [
'**/*.css',
'**/bootstrap.js',
'**/routes.js',
'**/conf.js',
'**/app.js'
],
// 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_DEBUG,
// 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', 'Chrome', 'Firefox'],
plugins: [
'karma-*',
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
and my test-main.js file:
var testPaths = {
'customersControllersTest': '../test/customersControllersTest'
}, tests = Object.keys(window.__karma__.files).filter(function(file) {
return (/(spec|Test)\.js$/i.test(file));
}).map(function(test) {
var returnVal = false;
Object.keys(testPaths).map(function(path){
if(testPaths[path] === test.replace('/base', '..').replace('.js', '')) {
returnVal = path;
}
});
return returnVal;
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base/app',
paths: {
'jquery': '../scripts/jquery',
'angular': '../scripts/angular',
'angularMocks': '../scripts/angular-mocks',
// Modules
'servicesModule': './services/module',
'directivesModule': './directives/module',
'controllersModule': './controllers/module',
// Controllers
'testController': './controllers/testController',
'ordersController': './controllers/ordersController',
'allordersController': './controllers/allordersController',
'customersController': './controllers/customersController',
// Directives
'barChart': './directives/barsChartDirective',
'blueBarChart': './directives/blueBarsChartDirective',
// Services
'testService': './services/testService',
'routeResolver': './services/routeResolver',
'customersFactory': './services/customersFactory',
// Tests
'customersControllersTest': '../test/customersControllersTest'
},
// angular does not support AMD out of the box, put it in a shim
shim: {
'angular': {
deps: ['jquery'],
exports: 'angular'
},
'angularRoute': ['angular'],
'angularAnimate': ['angular'],
'angularMocks': ['angular']
},
// dynamically load all test files
deps: tests,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start()
});
and my customersControllersTest.js:
define('customersControllersTest', [], function() {
describe('test', function() {
console.log(this);
it('test1', function() {
expect('this').toEqual('this');
});
console.log(this);
});
});
By checking in Chrome's devtools, it gives an Error:
but when I open it:
This however might be completely unrelated, since I keep getting the following:
which, asides for saying it found no test, is yelling Error...
Any ideas on how I can tackle this?
One problem is the line:
callback: window.__karma__.start()
This calls start right away instead of passing it as callback. This line should have been
callback: window.__karma__.start
See karma-requirejs README.
I am trying to configure my karma jasmine unit testing with requirejs. But each time i run it, i am getting the below error:
Chrome 34.0.1847 (Mac OS X 10.9.2) ERROR
Uncaught Error: Mismatched anonymous define() module: function (angular){
describe('Unit: Testing RequireJS', function(){
var ctrl;
var scope;
var rootScope;
beforeEach(angular.mock.module('wsaApp'));
beforeEach(angular.mock...<omitted>...ch
Below are differenr file:
spec file:
define(['angular'], function(angular){
describe('Unit: Testing RequireJS', function(){
var ctrl;
var scope;
var rootScope;
beforeEach(angular.mock.module('wsaApp'));
beforeEach(angular.mock.inject(function($rootScope){
scope = $rootScope.$new();
rootScope = $rootScope;
}));
});
});
main.js
require.config({
paths: {
/* ABC order */
'angular': 'vendor/angular/1.2.0/angular.min'
},
shim: {
'angular': { exports: 'angular' },
'app/controllers': { deps: ['angular'] }
}
});
test-main.js
// This creates an array of all the files that Karma finds with a suffix of
// Test.js (eg utilsTest.js) to be added to the Require JS config below
var tests = [],
file;
for (file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if(/spec\.js$/.test(file)) {
tests.push(file);
}
}
}
requirejs.config({
baseUrl: '/base/public/javascripts/', // Karma serves files from /base/<your-base-path>
paths: {
/* ABC order */
'angular': 'vendor/angular/1.2.1/angular.min'
},
shim: {
'angular': { exports: 'angular' },
'app/controllers': { deps: ['angular'] },
},
deps: tests, // add tests array to load our tests
callback: window.__karma__.start // start tests once Require.js is done
});
karma.conf.js
//Karma configuration
module.exports = function (config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// Fix for "JASMINE is not supported anymore" warning
frameworks: ["jasmine", "requirejs"],
// list of files / patterns to load in the browser
files: [
'vendor/angular/1.2.1/angular.js',
'jquery-1.7.1.min.js',
'test/spec/**/*.js',
'test/test-main.js'
],
preprocessors: {
'app/**/*.js': 'coverage'
},
// list of files to exclude
exclude: ['app/main.js'],
// test results reporter to use
// possible values: dots || progress || growl
reporters: ['progress', 'coverage'],
coverageReporter : {
type: 'html',
dir: 'coverage/'
},
// web server port
port: 9876,
// cli runner port
runnerPort: 9100,
// enable / disable colors in the output (reporters and logs)
colors: true,
// 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,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
browserNoActivityTimeout: 100000,
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 20000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
});
}
i have tried different options mentioned in other threads, but nothing seems to work.
Finally i solved all the issues and was able to run the jasmine test successfully with requirejs configuration. I had top mention all the dependencies in the karma config and mark them as included: false exclusively so that they get loaded by requirejs through my test-config file.
files: [
{pattern: 'vendor/angular/1.2.1/angular.js', included: false},
{pattern: 'vendor/angular/1.2.1/angular-mocks.js', included: false},
{pattern: 'vendor/angular/1.2.1/angular-*.js', included: false},
{pattern: 'vendor/bootstrap/bootstrap-*.js', included: false},
{pattern: 'jquery-1.7.1.min.js', included: false},
{pattern: 'app/app.js', included: false},
{pattern: 'app/**/*.js', included: false},
{pattern: 'test/test-config.js', included: true}]
only the test-config is loaded through karma and all others to be included in the karma config but mark as false.
Also, i had to load the app.js in my spec file so that the modules and controllers get loaded:
define(['angular-mocks', 'jquery', 'app/app'], function(angularmocks, $, app){
describe.....
}
Since you're loading the specific .js files you need in your test-main.js with the paths: { } parameter, you don't have to explicitly list them in karma.config.js. Instead, you can just use your line { pattern: 'app/**/*.js', included: false }. All the lines before that are redundant. Just make sure you have the included: false modifier, otherwise Karma will load them in-line, and you'll get the Uncaught Error: Mismatched anonymous define() problem