How to remove module not found error in angular? - angularjs

I make a simple example of controller here .
http://plnkr.co/edit/dplJ6sf4kgiwJ5pXu4GE?p=preview
and I want to test the controller .I am able to test my controller online
Here is my code to test my controller online
http://plnkr.co/edit/xzvhXHPoUdulOM9clOkQ?p=preview
But when I try to run that same work on my computer my test case are fail
I am getting error this
Module 'app.home' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Here is my computer code.
https://dl.dropbox.com/s/no901z41bza7osm/SimpleDemo.zip?dl=0
Please run npm install to add dependency .
Here is my karma.conf.js file
// Karma configuration
// Generated on Fri Dec 18 2015 19:53:32 GMT+0530 (IST)
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: [
'bower_components/angular/angular.js' ,
'bower_components/jquery/dist/jquery.js' ,
'bower_components/angular-ui-router/release/angular-ui-router.js' ,
'bower_components/angular-mocks/angular-mocks.js' ,
'bower_components/angular-resource/angular-resource.js' ,
'app/*.js',
'app/**/*.js',
'app/**/*.html',
'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: {
'app/**/*.html':['ng-html2js']
},
ngHtml2JsPreprocessor:{
moduleName:'templates'
},
// 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 simultanous
concurrency: Infinity
})
}
here is my code testing
(function(){
'use strict'
describe('http controller test', function() {
var $rootScope,
$scope,
controller,
$q,
$httpBackend;
beforeEach(function() {
module('app');
inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
controller = $injector.get('$controller')('homeCntrl', {
$scope: $scope
})
})
})
describe('Init value', function() {
it('check name value', function() {
expect(controller.message).toBeUndefined();
})
})
it('it should be true', function() {
expect(true).toBeTruthy();
})
})
})()
any update ?how to do testing of controller?
update 1
when I write like that it is not working ...check these file
'app/**/*.js',
'app/*.js',
'app/home/controller/*.js',
'app/**/*.html',
'test/**.js'
whole code
files: [
'bower_components/angular/angular.js' ,
'bower_components/jquery/dist/jquery.js' ,
'bower_components/angular-ui-router/release/angular-ui-router.js' ,
'bower_components/angular-mocks/angular-mocks.js' ,
'bower_components/angular-resource/angular-resource.js' ,
'app/**/*.js',
'app/*.js',
'app/home/controller/*.js',
'app/**/*.html',
'test/**.js'
],
but when I write like that it work perfectly why ?
files: [
'bower_components/angular/angular.js' ,
'bower_components/jquery/dist/jquery.js' ,
'bower_components/angular-ui-router/release/angular-ui-router.js' ,
'bower_components/angular-mocks/angular-mocks.js' ,
'bower_components/angular-resource/angular-resource.js' ,
'app/home/*.js',
'app/app.js',
'app/home/controller/*.js',
'app/**/*.html',
'test/**.js'
],

Change homeCntrl to homecntrl
In your route.js in this line: controller:'homeCntrl as home'

Related

Unit Testing an Angular Service using Karma and Jasmine

I am new to angular and TDD in angular
I want to test drive a service, but before that wanted to understand the flow. I am having a few issues. I keep getting this error
Firefox 47.0.0 (Windows 10 0.0.0) ERROR
Error: [$injector:nomod] http://errors.angularjs.org/1.5.7/$injector/nomod?p0=myApp
at C:/domain/domain/test/unitTest/spec/client/lib/angular.min.js:6
My app.js file is as follow
angular.module('myApp', [
'smart-table',
'ngRoute',
'ng-bs3-datepicker',
'angucomplete-alt',
'angular-loading-bar',
'checklist-model',
'ngFileUpload',
'ui.bootstrap'
])
.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
//some code here
}])
My services.js code is as follows
angular.module('myApp')
.service('usersLocationService', function () {
this.SetLocation = function (place) {
var address = {};
//some code here
return address;
};
}
My karma.conf.js file is as follows
// 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', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'test-main.js',
'test/unitTest/spec/client/lib/angular.min.js',
'test/unitTest/spec/client/lib/angular-mocks.js',
'public/Controllers/**/*.js',
'public/Controllers/subDomain/**/*.js',
'https://code.jquery.com/jquery-1.11.2.min.js',
'test/unitTest/spec/client/**/*.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: ['Firefox'],
// 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
})
}
And finally my unitTest case code is
"use strict";
describe('Test Suite for UserLocationService', function () {
beforeEach(angular.module.mock('myApp'));
beforeEach(inject(function (_usersLocationService_) {
this.sut = _usersLocationService_;
}));
it('Should return the address from the google location place', function() {
var place = {};
var data = this.sut.SetLocation(place);
console.log(data);
});
});
There is no angular.module.mock function. It is
angular.mock.module('myApp')

How to test html tags in karma test

I want to test my html tags(text,div,span,etc...)
I am using angularjs,karma with jasmine framework.
This my karma file, here i include ng-html2js preprocess.
// Karma configuration
// Generated on Tue Jan 26 2016 21:38:16 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: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'../app/js/base.js',
'../global_URL.js',
'../app/**/*.html',
'bower_components/angular-mocks/angular-mocks.js',
'../app/js/app.js',
'test/spec/**/*.js',
'../app/**/*.json'
],
// 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/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
moduleName: 'templates'
},
// 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: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
plugins: [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-ng-html2js-preprocessor'
],
// 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
})
}
For getting html page i am using httpBackend, my test file like this.
'use strict';
describe('Login Controller', function () {
// load the controller's module
var MainCtrl,
httpBackend,
templateHtml
formElem,
form,
scope;
beforeEach(module('test'));
beforeEach(module('templates'));
beforeEach(module('ngMockE2E'));
//beforeEach(module('sample',['ngMock']));
// Initialize the controller and a mock scope
beforeEach(inject(function ($rootScope, $controller,$compile,$httpBackend,$templateCache) {
scope = $rootScope.$new();
httpBackend = $httpBackend
MainCtrl = $controller('TestController', {
$scope: scope,
});
templateHtml = httpBackend.expectGET('app/admin/login.html').respond([]);
console.log(templateHtml)
formElem = angular.element("<div>test</div>")
$compile(formElem)(scope)
form = scope.form
scope.$apply()
}));
it('should not allow an invalid `width`', function() {
expect(form).toBeDefined();
});
});
Here i print my html page in console, but it's wrote as undefined.
How can i inject my html pages in karma and how can i test html tags.
Please help me, thanks in advance.
to preload html we use the following karma.conf.js ...
'use strict';
module.exports = function (config) {
config.set({
basePath: './',
browsers: ['PhantomJS'],
frameworks: ['jasmine'],
reporters: ['mocha', 'coverage'],
singleRun: true,
preprocessors: {
'src/**/!(*spec)*.js': ['coverage'],
'dest/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'dest/',
moduleName: 'ngHtmlFiles'
},
coverageReporter: {
type: 'html',
dir: 'coverage'
},
files: [
'dest/vendor.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/**/*.js',
'dest/**/*.html'
]
});
};
then in each test ...
beforeEach(module('ngHtmlFiles'));
This will preload the HTML.
However, we do this for a totally different reason to you, namely to prevent httpBackend failing expectations when requests for HTML files are made.
I personally would use protractor E2E testing to test the UI. I believe unit tests should be limited to testing controller / service code only.

angular Failed to instantiate module myModule issue

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

Issue with angular.mock.inject method

I am using folloing jasmine test case
'use strict';
describe('companyService', function() {
var $httpBackend, companyService;
beforeEach(angular.mock.module('myApp'));
beforeEach(angular.mock.inject(function(_$httpBackend_ , _companyService_) {
$httpBackend = _$httpBackend_;
companyService = _companyService_;
}));
it('should return a promise for getCompany function', function() {
// expect(typeof companyService.getCompany('foobar').then).toBe('function');
});
});
i am getting the following error . as you can see above . i am not doing anything inside it block .
minErr/<#C:/Users/userone/Documents/myAppPkg/myApp/WebApiRole/bower_components/angular/angular.js:63:12
loadModules/<#C:/Users/userone/Documents/myAppPkg/myApp/WebApiRole/bower_components/angular/angular.js:4138:15
forEach#C:/Users/userone/Documents/myAppPkg/myApp/WebApiRole/bower_components/angular/angular.js:323:11
loadModules#C:/Users/userone/Documents/myAppPkg/myApp/WebApiRole/bower_components/angular/angular.js:4099:5
createInjector#C:/Users/userone/Documents/myAppPkg/myApp/WebApiRole/bower_components/angular/angular.js:4025:11
workFn#C:/Users/userone/Documents/myAppPkg/myApp/WebApiRole/node_modules/angular-mocks/angular-mocks.js:2425:44
irefox 38.0.0 (Windows 8.1): Executed 1 of 1 (1 FAILED) ERROR (0.251 secs / 0.008 secs)
I assume this issue comes because of the angular.mock.inject method i have been using . because the execution does not enter the following block
beforeEach(angular.mock.inject(function(_$httpBackend_ , _companyService_) {
$httpBackend = _$httpBackend_;
companyService = _companyService_;
}));
Karma.conf.js file
// Karma configuration
// Generated on Thu May 21 2015 16:24:51
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: [
'bower_components/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'app/app.js',
'app/*.js',
'app/**/*.js',
'app/**/**/*.js',
'app/company/CompanyService.js',
'test/company/*.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
hostname: 'localhost',
port: 44555,
// 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: ['Firefox'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
can any one help me out with this . ?
You should update the "karma-chrome-launcher" and "karma-firefox-launcher" in node_module.
This may be solve the issue.
npm install karma-chrome-launcher
npm install karma-firefox-launcher
If you think the issue because of "angular.mock.inject " then one can use inject function.
But I think your unit test script is not getting chance for loading and execution.So,this will not reason for above error.
Thanks.
I found out the solution for this problem. Turns out i have missed some dependencies in the karma.conf.js . When you missed dependencies , the $inject method does not get executed . What i did was , from the index.html , copied all the dependencies (from bower componants folder and node_modules folder) and put them in the karma.conf.js under files .
for example , i have copied all the file dependencies from index.html and put it under files
'bower_components/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'bower_components/jquery/dist/jquery.js',
'bower_components/pnotify/pnotify.core.js',
'bower_components/pnotify/pnotify.buttons.js',
'bower_components/pnotify/pnotify.confirm.js',
'bower_components/pnotify/pnotify.desktop.js',
'bower_components/pnotify/pnotify.nonblock.js',
'bower_components/pnotify/pnotify.callbacks.js',
'bower_components/pnotify/pnotify.history.js',
'bower_components/pnotify/pnotify.reference.js',
'bower_components/jquery-ui/jquery-ui.min.js',
'bower_components/bootstrap/dist/js/bootstrap.js',
'js/fullcalendar.min.js',
'js/daterangepicker.min.js',
'bower_components/moment/moment.js',
'bower_components/moment-timezone/builds/moment-timezone-with-data-2010-2020.js',
'bower_components/angular-i18n/angular-locale_no.js',
'bower_components/ng-file-upload/angular-file-upload.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-translate/angular-translate.js',
'bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
'bower_components/angular-pnotify/src/angular-pnotify.js',
'bower_components/angular-local-storage/angular-local-storage.js',
'bower_components/angular-loading-bar/build/loading-bar.min.js',
'bower_components/angular-moment/angular-moment.js',
'bower_components/angular-bootstrap-switch/dist/angular-bootstrap-switch.js',
'bower_components/bootstrap-switch/dist/js/bootstrap-switch.js',
'app/app.js',
'app/**/*.js',
'test/**/*Spec.js'

angular - requireJs - karma

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

Resources