Uncaught Error: [$injector:nomod] Module 'app' is not available - angularjs

I am new to angularjs and I am facing this error while i run my test using karma-jasmine
Uncaught 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 dependencies as the second argument.
http://errors.angularjs.org/1.6.6/$injector/nomod?p0=app
at bower_components/angular/angular.js:2297
describe('LoginController', function () {
beforeEach(module('app'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('homeBtn', function () {
it('whether its sign in or register', function () {
var $scope = {};
var controller = $controller('LoginController', { $scope: $scope });
$scope.homeBtn("Register");
expect($scope.signinerror).toBeFalsy();
expect($scope.tryagain).toBeFalsy();
expect($scope.registererror).toBeFalsy();
expect($scope.modal_title).toBe("Register");
});
});
});
this is my app.js
var app = angular.module('app', ['ngRoute','ngWebSocket','ng.epoch']);
This is my Login Controller
angular.module('app').controller('LoginController',['$rootScope','$scope','$location','$http', function($rootScope,$scope,$location,$http){
$scope.homeBtn = function(keyvalue){
$scope.signinerror=false;
$scope.tryagain=false;
$scope.registererror=false;
if(keyvalue == "Register"){
$scope.modal_title="Register";
$scope.reg=true;
}
else{
$scope.reg=false;
$scope.modal_title="Sign In";
}
}
Here is my HTML code
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet"href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="bower_components/epoch/dist/css/epoch.min.css">
<link rel="stylesheet" href="app/css/index.css">
</head>
<body>
<ng-view> </ng-view>
<!--Bower Components-->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="bower_components/angular-websocket/dist/angular-websocket.min.js"></script>
<script src="bower_components/d3/d3.js"></script>
<script src="bower_components/epoch/dist/js/epoch.min.js"></script>
<script src="bower_components/ng-epoch/ng-epoch.js"></script>
<script src="bower_components/js-md5/src/md5.js"></script>
<!--MainJS-->
<script src="app/js/app.js"></script>
<!--Controllers-->
<script src="app/js/Controllers/LoginController.js"></script>
<script src="app/js/Controllers/HomeController.js"></script>
<!--custom js files-->
<script src="app/js/libraries/common.js"></script>
<script src="app/js/libraries/smoothie.js"></script>
<!--directives-->
<!--factories-->
<script src="app/js/Factories/websocketservice.js"></script>
</body>
</html>
and here is my 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: ['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 simultaneous
concurrency: Infinity
})
}

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')

Karma + RequireJS + AngularJS, shimmed scripts not loading in spec

While using Karma + Jasmine + RequireJS + AngularJS, I'm unable to load any of my shimmed scripts, for example angular-mocks, into the test specs. The file seem to be served all right, just doesn't work in the spec.
UPDATE Angular is global, and the corresponding shim doesn't affect it.
In Karma.conf.js, I'm including angular-mocks to be loaded by RequireJS:
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: 'node_modules/angular-mocks/angular-mocks.js', included: false},
...
'test/euro-2016/main-test.js'
],
// list of files to exclude
exclude: [
'main/main-euro-2016.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'../../*.html': ['ng-html2js']
},
// 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,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
};
The RequireJS shim in the Karma main file main-test.js:
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
}
requirejs.config({
// Karma serves files from '/base'
baseUrl: "/base",
paths: {
"angular": "vendor/angular/angular",
"angularMocks": "node_modules/angular-mocks/angular-mocks",
"jquery": "vendor/jquery/jquery.min",
...
},
shim: {
"angular": {
exports: "angular",
deps: ['jquery']
},
"angularMocks": {
exports: "angularMocks",
deps: ['angular']
},
...
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
});
The spec file:
define(['angular', 'modules/euro-2016/app', 'angularMocks'], function(angular, app, mocks){
console.log("ANGULAR", angular); // ok
console.log("APP", app); // ok
console.log("MOCKS", mocks); // undefined
})
Looking at the source code that is installed by installing the NPM package angular-mocks, specifically the file node_modules/angular-mocks/angular-mocks.js, here is what I see:
There is no mention of angularMocks anywhere in that code, therefore exporting angularMocks cannot work.
Conversely, the plugin installs itself as angular.mock. Early in the file there is the line:
angular.mock = {};
And then everything is added to angular.mock.
So you can remove your exports and access the plugin through angular.mock. This should work:
define(['angular', 'modules/euro-2016/app', 'angularMocks'], function(angular, app){
console.log("ANGULAR", angular);
console.log("APP", app);
console.log("MOCKS", angular.mock);
});
If you must have an exports for some reason (for instance if you use enforceDefine, which requires that all shim have exports values) you could set it to angular.mock.

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

Angular and Grunt

I'm a Grunt newbie and I'm trying to convert an Angular app (based on angular-seed) to use it for CSS/JS concat/minification. I have an index.html file that defines the CSS and JS files:
<!-- build:css css/myjmh.css -->
<link rel="stylesheet" href="lib/bootstrap/bootstrap.min.css"/>
<link rel="stylesheet" href="lib/font-awesome/font-awesome.min.css"/>
<link rel="stylesheet" href="lib/toaster/toaster.css"/>
<link rel="stylesheet" href="css/app.css"/>
<link rel="stylesheet" href="css/custom.css"/>
<link rel="stylesheet" href="css/responsive.css"/>
<!-- endbuild -->
...
<!-- build:js js/myjmh.min.js -->
<script src="lib/jquery/jquery-1.10.2.min.js"></script>
<script src="lib/bootstrap/bootstrap.min.js"></script>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular/angular-animate.min.js"></script>
<script src="lib/angular/angular-cookies.min.js"></script>
<script src="lib/angular/angular-resource.min.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="lib/fastclick.min.js"></script>
<script src="lib/toaster/toaster.js"></script>
<script src="lib/webshim/modernizr.min.js"></script>
<script src="lib/webshim/polyfiller.min.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
<!-- endbuild -->
I'm trying to use grunt-usemin and its useminPrepare task to grab these values from my HTML.
Here's my Gruntfile.js:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ["dist"],
copy: {
main: {
src: 'app/index.html',
dest: 'dist/index.html'
}
},
useminPrepare: {
html: 'app/index.html'
},
usemin: {
html: ['dist/index.html']
},
ngmin: {
dist: {
files: [
{
expand: true,
cwd: '.tmp/concat/js',
src: '*.js',
dest: '.tmp/concat/js'
}
]
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-ngmin');
grunt.loadNpmTasks('grunt-usemin');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', [
'copy', 'useminPrepare', 'concat', 'ngmin', 'uglify', 'cssmin', 'usemin'
]);
};
With all these settings, a "dist" directory is created with all the artifacts and everything seems to be generated/concatenated and minified correctly. However, when I load the new page up in my browser, I get the following error:
Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.2.3/$injector/unpr?p0=aProvider%20%3C-%20a
It seems like Grunt is doing something that doesn't play well with Angular. Any ideas on what this might be?
I was able to solve this by turning off mangling in uglify:
uglify: {
options: {
report: 'min',
mangle: false
}
}
As you might notice from my Gruntfile.js, ngmin is already used and this doesn't seem to help.
Found answer here: https://stackoverflow.com/a/17239358/65681
You need to do one of two things:
Make all of your angular code minification-friendly. See: http://docs.angularjs.org/guide/di#dependency-injection_dependency-annotation
Use a tool like grunt-ngannotate
If you are having same issues with declarations as I had, you could also use ng-annotate in order to achieve this. Here is a link to github: https://github.com/mzgol/grunt-ng-annotate
My working configuration is:
ngAnnotate: {
options: {
singleQuotes: true,
regexp: '^(ng\n?[\\ ]+(.*)|(module.*))$'
},
prod: {
files: [{
expand: true,
src: 'dist/**/*.js'
}]
}
}
Use it carefully as it will modify existing files. My assumption is that files in 'dist' folder should be generated by Grunt and can be deleted at any time.
As others have stated, it seems that you have a problem with minification. I see that you're using ngmin. But ngmin may not work when a file with mixed patterns is thrown at it. I mean, make sure that all of the files that you pass to ngmin don't already have minification-safe pattern.
Mangle false shouldn't be the solution, actually the code is not minification friendly, but the issues that I had were not explicitly described here, so they were:
1) "Make sure you only define each module with the angular.module(name, [requires]) syntax once across your entire project. Retrieve it for subsequent use with angular.module(name)" - I used it wrong in many places and it worked with mangle:false, breaking when setting mangle:true
2) I used bootstrap modal windows specifying instance controller not as a string, I've found the solution here

Resources