Failed to instantiate module, KARMA - angularjs

I've finished to implement my web site with AngularJS and now, I must make my unit test to verify the correct functioning of my functions.
I was looking for a lot of tutorial on internet but apparently, my application structure doesn't allow testing with karma and jasmin.
Let me explain, I got a site web with just one single page HTML which is linked with one controller (a file .js) I've never installed Angular with NPM but I've imported it with:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
And I load my controller with:
<script src="main.js"></script>
and some other imported script.
I would like to try my controller with unit tests, so I've created a package.json file and installed karma, jasmine, and karma-cli with npm.
I've make a folder called "Tests" and created a test.js file:
describe("App",() =>{ //Describe object type
beforeEach(module('App')); //Load module
describe('Ctrl',()=>{
var Ctrl;
beforeEach(inject( ($injector)=>{ //instantiate controller using $controller service
$rootScope = $injector.get('$rootScope');
$controller = $injector.get('$controller');
$scope = $rootScope.$new();
}));
beforeEach(inject(($controller)=>{
Ctrl = $controller("Ctrl");
}));
it("Should say hello",()=>{
expect(Ctrl.msg).toBe("Hello");
})
})
})
But when I use:
karma start
it's doesn't detect my controller.
Here is my console output:
Here is my karma.conf.js:
// Karma configuration
// Generated on Thu Jun 14 2018 16:51:15 GMT+0200 (Paris, Madrid (heure d’été))
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: [ 'Scripts/angular.js','Scripts/angular-mocks.js','main.js','Tests/*.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: {
},
// 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
})
}
And how i declare my controller :
var app = angular.module('App', ['ngMaterial', 'ngMessages'])
app.controller('Ctrl', ['$rootScope', '$scope','$http','$timeout','$mdDialog','Global', 'projects', 'screens', 'users', 'licenses', function($rootScope, $scope, $http, $timeout, $mdDialog,Global, projects, screens, users, licenses) {
...
}
Here is my tree folder :
-Root
|---node_modules
|---Tests
| |---test.js
|---Scripts
|---index.html
|---main.js <--- controller of my index.html
|---style.css
|---someFactory.js
I don't think I'm doing it in the right way. Please, explain me how to do it.

Related

Angular services not being defined in beforeEach in Karma

I have an Angular Application using Jasmine and Karma for testing.
This is my testing class:
var data = require('./user.mock.js');
describe('Service: UserService', function () {
var ServerUrl;
var httpBackend;
var userService;
beforeEach(angular.mock.module('myModule'));
beforeEach(angular.mock.inject(function (_userService_, $httpBackend, _ServerUrl_) {
userService = _userService_;
httpBackend = $httpBackend;
ServerUrl = _ServerUrl_;
}));
describe('when get the active users from backend', function () {
// given
beforeEach(function () {
httpBackend
.whenGET(ServerUrl + '/users')
.respond(angular.copy(data.activeUsers));
});
it('should return the list of active users', function () {
var expectedUsers = angular.copy(data.activeUsers);
expectedUsers[0].profilePicture = ServerUrl + '/pictures/' + expectedUsers[0].id + '/small/show';
expectedUsers[1].profilePicture = ServerUrl + '/pictures/' + expectedUsers[1].id + '/small/show';
userService
.listUsers()
.then(function(users) {
expect(users).toEqual(expectedUsers);
});
httpBackend.flush();
});
});
And this is my karma conf:
// 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/angular/angular.js",
"bower_components/angular-mocks/angular-mocks.js",
"bower_components/angular-animate/angular-animate.js",
"bower_components/angular-bootstrap/ui-bootstrap-tpls.js",
"bower_components/angular-cookies/angular-cookies.js",
"bower_components/angular-gettext/dist/angular-gettext.js",
"bower_components/angular-http-auth/src/http-auth-interceptor.js",
"bower_components/angular-notify/dist/angular-notify.js",
"bower_components/angular-resource/angular-resource.js",
"bower_components/angular-route/angular-route.js",
"bower_components/angular-sanitize/angular-sanitize.js",
"bower_components/angular-touch/angular-touch.js",
"bower_components/angular-ui-utils/ui-utils.js",
"bower_components/angular-ui-map/ui-map.js",
"bower_components/bootstrap-sass/assets/javascripts/bootstrap.js",
"bower_components/bootstrap-select/dist/js/bootstrap-select.js",
"bower_components/event-signal/dist/event-signal.min.js",
"bower_components/google-map-infobubble/src/infobubble.js",
"bower_components/moment/moment.js",
"bower_components/ng-file-upload/ng-file-upload.js",
"bower_components/ng-file-upload-shim/ng-file-upload-shim.js",
"bower_components/angularUtils-pagination/dirPagination.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']
},
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
});
};
When I run karma test from the command line, the services injected do not get recognized. I am suspecting that the inject function is not being called in the beforeEach method, but I am not sure. I am getting undefined in the tests, as if the variable never got any value.
workFn#/Users/brunosiqueira/WebstormProjects/copcast-admin/bower_components/angular-mocks/angular-mocks.js:2507:60
TypeError: undefined is not an object (evaluating 'httpBackend
.whenGET') in /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify (line 5994)
/var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify:5994:18
TypeError: undefined is not an object (evaluating 'userService
.getUserVideos') in /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify (line 6012)
/var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify:6012:18
Can you guys help me?
Two things I remember:
The order of the JS files has to be right in the config files
The usage seems grossly right and is this. Just check if this makes a
difference :
beforeEach(inject(function($controller, $rootScope, _myService_){
scope = $rootScope.$new();
myServiceSvc = _myService_;
firstCtrl = $controller("firstCtrl",{
$scope: scope,
myService: myServiceSvc
});
}));
karma.conf
files: [
'index.html',
'lib/angular.min.js',
'lib/angular-ui-router.min.js',
'lib/angular-mocks/angular-mocks.js',
'lib/app.js',
'tests/controller/basics.js'
],
In the end it just a stupid error (as most of them are).
Using git bisect, I was able to find the commit where the tests stopped working.
In that commit, I saw that I added the ng-jwplayer dependency to the project. The library requires a javascript call before it the html file.
'https://content.jwplatform.com/libraries/XXXXXX.js',
That url was missing in the karma.conf files array. It was generating an error:
files: [
'http://maps.googleapis.com/maps/api/js?sensor=false&language=en',
'https://content.jwplatform.com/libraries/XXXXXX.js',
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-gettext/dist/angular-gettext.js',
'bower_components/angular-http-auth/src/http-auth-interceptor.js',
'bower_components/angular-notify/dist/angular-notify.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-ui-utils/ui-utils.js',
'bower_components/angular-ui-map/ui-map.js',
'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'bower_components/bootstrap-select/dist/js/bootstrap-select.js',
'bower_components/event-signal/dist/event-signal.min.js',
'bower_components/google-map-infobubble/src/infobubble.js',
'bower_components/moment/moment.js',
'bower_components/ng-jwplayer/jwplayer.min.js',
'bower_components/ng-file-upload/ng-file-upload.js',
'bower_components/ng-file-upload-shim/ng-file-upload-shim.js',
'bower_components/angularUtils-pagination/dirPagination.js',
// endbower
'src/app/**/*.js',
'src/app/views/**/*.html',
'src/test/**/*.js'
],
With the url included, the files work well. This was another case of misleading error message.

Module 'templates' is not available! in angular js?

I am trying to test directive in angular using Jasmine. I installed karma-ng-html2js-preprocessor using NPM. Then I istalled jQuery using Bower but I am getting this error
Connected on socket ndfTI8XJInIU5YJCAAAA with id 49983199
Chrome 47.0.2526 (Mac OS X 10.10.2) http controller test it should be one FAILED
Error: [$injector:modulerr] Failed to instantiate module templates due to:
Error: [$injector:nomod] Module 'templates' 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.
http://errors.angularjs.org/1.4.8/$injector/nomod?p0=templates
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:68:12
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:2005:17
at ensure (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:1929:38)
at module (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:2003:14)
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/a
I made directive like this
angular.module('app',[]).controller('first',function($scope,data){
$scope.name='test';
$scope.message='application';
data.getData().then(function(data){
console.log(data);
})
}).factory('data',function($http){
return{
getData:getData
}
function getData(){
return $http.get('data.json').success(successCall).error(errorcallback)
}
function successCall(data){
return data
}
function errorcallback(data){
return data
}
}).directive('helloWorld',function(){
return {
restrict:'E',
scope:{
data:'=',
message:'#'
} ,
templateUrl:'app/partial/home.html',
link:function(s,e,a){
}
}
})
home.html
<div class="dir">
<h1>{{data}}</h1>
<h1>{{message}}</h1>
</div>
test.js
describe('http controller test', function () {
var $rootScope,
$scope,
$compile,
$body=$('body'),
el,
$el,
controller,
html='<hello-world data="name" message="{{message}}"></hello-world>';
beforeEach(function(){
module('templates','app') ;
inject(function($injector){
$rootScope = $injector.get('$rootScope') ;
$compile = $injector.get('$compile') ;
$scope=$rootScope.$new();
el=$compile(angular.element(html))($scope)
controller =$injector.get('$controller')('first',{$scope:$scope})
})
$body.append(el);
$rootScope.$digest();
$el=$('.dir');
})
afterEach(function(){
$body.empty();
})
it('it should be one',function(){
expect($el.length).isEqual(1)
})
describe('Init value',function(){
it('check name value',function(){
expect($scope.name).toEqual('test');
})
})
it('it should be true',function(){
expect(true).toBeTruthy();
})
})
and there is karma-config 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-mocks/angular-mocks.js' ,
'bower_components/angular-resource/angular-resource.js' ,
'app/**/.html',
'app/*.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: {
'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
})
}
I already declared the template module like this
ngHtml2JsPreprocessor:{
moduleName:'templates'
},
update 1
Connected on socket i5kkzULDwF1_ptvcAAAA with id 55433592
Chrome 47.0.2526 (Mac OS X 10.10.2) http controller test it should be one FAILED
Error: [$injector:modulerr] Failed to instantiate module templates due to:
Error: [$injector:nomod] Module 'templates' 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.
http://errors.angularjs.org/1.4.8/$injector/nomod?p0=templates
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:68:12
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:2005:17
at ensure (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:1929:38)
at module (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:2003:14)
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:4435:22
at forEach (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:340:20)
at loadModules (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:4419:5)
at Object.createInjector [as injector] (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:4344:11)
at Object.workFn (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular-mocks/angular-mocks.js:2428:52)
at window.inject.angular.mock.inject (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular-mocks/angular-mocks.js:2411:37)
http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=templates&p1=Error%3A%20%5B%24injector%3Anomod%5D%20Module%20'templates'%20is%20not%20available!%20You%20either%20misspelled%20the%20module%20name%20or%20forgot%20to%20load%20it.%20If%
I have no prior experiences with karma-ng-html2js-preprocessor so this is more like a guess - could it be that template module was not generated because no templates were found.
Could you try to change this part of files section of your karma-config from:
'app/**/.html'
to:
'app/**/*.html'
and preprocessors section from:
preprocessors: {
'app/**/.html':['ng-html2js']
}
to
preprocessors: {
'app/**/*.html':['ng-html2js']
}
Update:
If that doesn't work for you, you could set log level of Karma to
logLevel: config.LOG_DEBUG
and try to search for lines starting with DEBUG [preprocessor.html2js] to gather additional info related to html2js preprocessor.

how to include module in angular?

I am trying to do testing using jasmine .When I run this command karma start karma.conf.js it give me this error.
Chrome 47.0.2526 (Windows 7 0.0.0) Firstcontroller Initialization title should be naveen FAILED
Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the depend
encies as the second argument.
http://errors.angularjs.org/1.4.8/$injector/nomod?p0=app
at D:/Webapplication/karmaTest/bower_components/angular/angular.js:68:12
at D:/Webapplication/karmaTest/bower_components/angular/angular.js:2005:17
at ensure (D:/Webapplication/karmaTest/bower_components/angular/angular.js:1929:38)
at module (D:/Webapplication/karmaTest/bower_components/angular/angular.js:2003:14)
at D:/Webapplication/karmaTest/bower_components/angular/angular.js:4435:22
at forEach (D:/Webapplication/karmaTest/bower_components/angular/angular.js:340:20)
at loadModules (D:/Webapplication/karmaTest/bower_components/angular/angular.js:4419:5)
at Object.createInjector [as injector] (D:/Webapplication/karmaTest/bower_components/angular/angular.js:4344:11)
at Object.workFn (D:/Webapplication/karmaTest/bower_components/angular-mocks/angular-mocks.js:2428:52)
at window.inject.angular.mock.inject (D:/Webapplication/karmaTest/bower_components/angular-mocks/angular-mocks.js:2411:37)
I install karma , karma-jasmine ,karma-chrome launcher ..When I run simple test like expect(true).toBeTruthy it works fine.But when I am trying to test my controller .it gives me above error .
here is my controller
//(function () {
// 'use strict';
//
// angular.module('app',[]).controller('FirstController',FirstController);
//
// FirstController.$inject=['$scope']
//
// function FirstController($scope){
// $scope.title='naveen';
// }
//
//})();
angular.module('app',[]).controller('FirstController',FirstController);
FirstController.$inject=['$scope'];
function FirstController($scope){
$scope.title='naveen';
}
here is my test-spec.js file
describe('Firstcontroller', function () {
var $rootScope,
$scope,
controller;
beforeEach(function () {
module('app');
inject(function ($injector) {
$rootScope = $injector.get('$rootScope');
$scope=$rootScope.$new();
console.log('==========================')
controller=$injector.get('$controller')('FirstController',{$scope:$scope});
})
})
describe('Initialization',function(){
it('title should be naveen',function(){
expect($scope.title).toEqual('naveen')
})
})
})
it give be above error why ?
I include the package in karma.config file
karma.config file
// Karma configuration
// Generated on Tue Dec 08 2015 18:55: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: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'app/**/.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: ['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
})
}
update
I insert my js file inside the app directory when I change this 'app/**/.js' to 'app/*.js' it works fine ..why it works ?
Module 'app' 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.
The module in your Angular code is 'apps' not 'app'.
Fix the spelling mistake and it should work.

AngularJS, Jasmine and issue writing spec tests

Okay, so I have a seed setup and I have Jasmin Running (Thank you so much SoEzPz for the help).
it appears my spec's won't run, I tried and isolated spec and it ran with no issue but when I try to write one on a controller it errors.
here is the controller.
//This is the about function that is used in the About Module.
'use strict';
app.controller('AboutController',// jshint ignore:line
['$scope',
function ($scope) {
$scope.message = 'This is the about page message from the controller';
}]);
a very basic controller
here is my test
'use strict';
describe('Controller: com/modules/AboutController', function() {
beforeEach(module('app'));
var AboutController,
scope;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
AboutController = $controller('AboutController', {
$scope: scope
});
}));
it('It should show the page message', function () {
expect(scope.greeting).toEqual("This is the about page message from the controller");
});
});
The spec returns this error
ReferenceError: module is not defined
at Suite.<anonymous> (http://localhost:8888/com/modules/about/aboutController_spec.js:5:16)
at addSpecsToSuite (http://localhost:8888/:801:25)
at Env.describe (http://localhost:8888/:771:7)
at jasmineInterface.describe (http://localhost:8888/:3277:18)
at http://localhost:8888/com/modules/about/aboutController_spec.js:3:1
am I missing something or is my spec written wrong ?
I am including the ngmock here is my Karma.conf file
// Karma configuration
// Generated on Tue Jul 28 2015 11:28:22 GMT-0400 (EDT)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'../src/lib/js/angular/angular.min.js',
'../src/lib/js/angular/angular-mocks.js',
'../src/com/**/*.js',
'../src/com/**/*_spec.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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
This was definitely deceptive, after playing around with the specs (thinking that the issue was in the actual specifications ) I found a test that ran fine, but still my other specs would not run, so what I did was I went back and took a hard look at my karma.conf file and while looking through some of the other examples I found I wasn't including enough in the way of bower components. so I added some more IE resources, cookies ect and low and behold all tests passed .
here is what I added under files for those who might be having the same issue
'bower_components/angular/angular.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'../src/com/**/*.js',
'../src/com/**/*_spec.js'

ngStorage breaking my application tests

I have an Angular app with a simple karma test and a very simple configuration using requirejs and Angular 1.2.28. My test is ok.
/**
* Created by jose on 7/12/2015.
*/
/*global module, inject */
define(['home', 'angularMocks','ngStorage'], function(app) {
'use strict';
describe('homeController', function () {
var scope, $location, createController;
beforeEach(module('homeApp'));
beforeEach(inject(function ($rootScope, $controller, _$location_) {
$location = _$location_;
scope = $rootScope.$new();
createController = function () {
return $controller('homeController', {
'$scope': scope
});
};
}));
it('should have message', function () {
var controller = createController();
$location.path('/');
expect($location.path()).toBe('/');
expect(scope.message).toEqual('This is Add new order screen');
});
});
});
My module:
/**
* Created by jose on 7/12/2015.
*/
'use strict';
define(['angular', 'angularRoute'], function(angular) {
var app = angular.module('homeApp', ['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'homeController'
})
.when('/404', {
templateUrl: 'partials/404.html',
})
.otherwise({
redirectTo: '/404'
});
}
]);
app.controller('homeController', function ($scope) {
$scope.message = 'This is Add new order screen';
});
return app;
});
Unfortunately, when I try to add ngStorage as a dependency for this module, it cannot works anymore. Even try to add ngStorage to my karma configuration raise an error like this:
Error: Mismatched anonymous define() module: function (app) {
It only happens when I try to use ngStorage, when I just comment it into my karma.conf file error disappears and everything works fine...
In case of not being possible using ngStorage with Karma there are another alternatives for ngStorage? thanks
karma.conf
// Karma configuration
// Generated on Mon Jul 13 2015 09:49:28 GMT-0300 (Hora est. Sudamérica Pacífico)
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',
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',
'bower_components/ngstorage/ngStorage.js',
{pattern: 'javascripts/*.js', included: false},
{pattern: 'test/**/*Spec.js', included: false}
],
// list of files to exclude
exclude: [
'javascripts/config.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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
Project is at github: https://github.com/jbarros35/node/tree/master/angulartemplate
kind regards.
It appears as though you are not the only one receiving errors trying to use Karma and ngStorage together. The guys at Karma have made some of their code available to help resolve the issue. You can check it out here:
https://github.com/gsklee/ngStorage/issues/117
If you look at the code of ngStorage you'll see that it calls define. So it is a proper AMD modules. Each AMD module you use in a Karma setup must be loaded with included: False in files:
{ pattern: 'bower_components/ngstorage/ngStorage.js', included: False }
Otherwise, Karma will load it with a script element, and you will get the error you got.
It's because of the async load feature of require js. Errors can be solved by this way
Go to the test-main.js.
add shim there in this way
shim:{
'yourJsModule':{
deps:['angular','yourApp']
}
}
replace "yourJsModule" with the your angular file you intend to test and the 'yourApp' with your angular module file...

Resources