Angular & Karma injector:modulerr - template Clip-two - angularjs

I want just run karma test inside a template called Clip-two.
when i start karma conf
karma start my.conf.js
this is my error:
25 05 2017 11:36:10.911:WARN [karma]: No captured browser, open http://localhost:9876/
Chrome 49.0.2623 (Mac OS X 10.7.5) Users factory should exist FAILED
Error: [$injector:modulerr] http://errors.angularjs.org/1.4.7/$injector/modulerr?p0=clip-two&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.4.7%2F%24injector%2Fmodulerr%3Fp0%3DngCookies%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.4.7%252F%2524injector%252Fnomod%253Fp0%253DngCookies%250A%2520%2520%2520%2520at%2520Error%2520(native)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A9876%252Fbase%252Fbower_components%252Fangular%252Fangular.min.js%253Fb6b56d0e096efc26e09d6...cc346%3A41%3A35)%0A%20%20%20%20at%20Object.workFn%20(http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fbower_components%2Fangular-mocks%2Fangular-mocks.js%3Fe9f36bdb59779aa33da5eab3dfd5ffda120d58aa%3A2427%3A52)
my karma confs is made by karma init command. I added all files only
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
angular: ['mocks'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.min.js',
'bower_components/angular-animate/angular-animate.min.js',
'bower_components/angular-touch/angular-touch.min.js',
'bower_components/angular-sanitize/angular-sanitize.min.js',
'bower_components/angular-ui-router/release/angular-ui-router.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/ngstorage/ngStorage.min.js',
'bower_components/angular-translate/angular-translate.min.js',
'bower_components/angular-translate-loader-url/angular-translate-loader-url.min.js',
'bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js',
'bower_components/angular-translate-storage-local/angular-translate-storage-local.min.js',
'bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.min.js',
'bower_components/oclazyload/dist/ocLazyLoad.min.js',
'bower_components/angular-breadcrumb/dist/angular-breadcrumb.min.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js',
'bower_components/angular-loading-bar/build/loading-bar.min.js',
'bower_components/angular-scroll/angular-scroll.min.js',
'STANDARD/assets/js/app.js',
'STANDARD/assets/js/main.js',
'STANDARD/assets/js/config.constant.js',
'STANDARD/assets/js/config.router.js',
'STANDARD/assets/js/services/agente.js',
'STANDARD/assets/js/controllers/inboxCtrl.js',
'STANDARD/assets/test/*.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_WARN,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
this is my unit test
describe('Users factory', function() {
// Before each test load our api.users module
beforeEach(module('clip-two'));
// Before each test set our injected Users factory (_Users_) to our local Users variable
var $controller;
beforeEach(angular.mock.inject(function(_$controller_){
$controller = _$controller_;
}));
// A simple test to verify the Users factory exists
it('should exist', function() {
expect($controller).toBeDefined();
});
});
and that my app.js
'use strict';
angular.module("clip-two", [
'ngAnimate',
'ngCookies',
'ngStorage',
'ngSanitize',
'ngTouch',
'ui.router',
'ui.bootstrap',
'oc.lazyLoad',
'cfp.loadingBar',
'ncy-angular-breadcrumb',
'duScroll',
'pascalprecht.translate',
]);
some advice?

The error says that there is a problem with ngCookies in your test.
And when I look at your karma conf file, I can't see the file containing ngcookies loaded.
You probably just need to add it in karma.conf to make it work.

Considering the error, it seems that when running karma, the host can't be reached.
Can you access your application through http://localhost:9876/?
You may try to run them again keeping your browser opened on the above address, I know it seems that it doesn't make sense, but on some systems this fixes the issue.
Then taking a look at your karma file, maybe there are some dependencies missing. Be sure that you are including all the files you need, otherwise also when your tests will run, you may have few failures.
But I can understand that now the important is that tests run :D

Related

Failed to instantiate module, KARMA

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.

Running unit test : Karma + Jasmine gives undefined function `controller` error

I'm trying to implement the unit testing in existing angular project. For that I've added Grunt-Karma
karma:
unit:
options:
frameworks: ['jasmine'],
singleRun: true,
browsers: ['PhantomJS'],
files: [bower js files + project dev/test js files]
Controller is,
angular.module('app.lol.ctrls', []).controller('LOLCtrl', [
'$scope', '$filter', 'Resource', '$log', function($scope, $filter, Resource, $log) {//some logic}
And test spec is
describe('Controller: LOLCtrl', function () {
beforeEach(module('app'));
var OrderCtrl;
var scope;
var filter;
var log;
var resource=someResourceWithSomeDataFunc;
beforeEach(inject(function ($controller, $rootScope, $filter, $log) {
scope = $rootScope.$new();
OrderCtrl = $controller('LOLCtrl', {
$scope: scope,
$filter: filter,
Resource: resource,
$log: log
});
}));
it('should have lolVar to be undefined', function () {
expect(scope.lolVar).toBeUndefined();
});
});
When I run the test, I'm getting error
PhantomJS 1.9.8 (Linux 0.0.0) Controller: LOLCtrl should have lolVar to be undefined FAILED
Error: [ng:areq] Argument 'LOLCtrl' is not a function, got undefined
http://errors.angularjs.org/1.3.20/ng/areq?p0=LOLCtrl&p1=not%20a%20function%2C%20got%20undefined
undefined
at assertArg ....
I tried the solutions like using angular.mock.module instead of module in beforeEach. Also I've double checked whether I'm including the controller file.
Also the app.lol.ctrls is injected in app itself. I tried beforeEach(module(app.lol.ctrls)), but that too gives same error.
Help would be greatly appreciated.
first I think you forgot to include the dependencies of your module. without knowing the complete structure of your app-code, I guess that the code, where you defined your controller should be
angular.module('app.lol.ctrls', ['app.lol', '/*maybe other dependecies*/']).controller('LOLCtrl', [ ]);
or did you have a own module file? then it should look like this:
angular.module('app.lol.ctrls').controller('LOLCtrl', [ ]);
after resolving these dependency-problems, have a look on your index.html. Did you included
<script src="bower_components/angular-mocks/angular-mocks.js"></script>?
if not, install angular-mocks and include it.
then, as a second step, go to your test spec and add change the beforeEach parts like this:
beforeEach(function(){
module('app.lol.ctrls');
module('ngMockE2E');
});
try to run your tests again. if you're getting the same error like before, have a look at your grunt-file. the list of your files included by karma looks a little bit strange for me. maybe this could be a problem too. for help, here a snipped from my grunt-file:
karma: {
options: {
frameworks: ['jasmine'],
files: [
'<%= dom_munger.data.appjs %>',
//this files data is also updated in the watch handler, if updated change there too
'bower_components/angular-mocks/angular-mocks.js',
'application/**/*-spec.js',
'application/**/*.html',
'base/**/*-spec.js',
'error/**/*.html',
'html/**/*.html',
'*.html',
'bower_components/**/*.html'
],
preprocessors: {
'**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
moduleName: 'templates'
},
logLevel: 'WARN',
reporters: ['mocha'],
captureConsole: true,
autoWatch: false,
singleRun: true
}
}
I hope, this will help you a little bit to resolve your problem.

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...

How to test an Angular app?

For simple application such as just a "Hello World" where do I write tests.
I have created a plnkr.
http://plnkr.co/edit/M0GAIE837G3s1vNwTyK8?p=info
Now this is a very simple plnkr, which does nothing but display Hello World.
Now if I want to write a test for this Application i.e for MainCtrl.. where do I plug it in ?
To run test with Angular-Karma-Jasmine:
You need to install nodejs, karma runs on top of node
You need to install karma from Node Packaged Modules from your command window execute: npm install -g karma
If you plan to run this with Chrome and Firefox and you are running this on windows you need to add 2 environment variables:
CHROME_BIN = [Crome installation path/chrome.exe]
FIREFOX_BIN =[Firefox installation path/firefox.exe]
4. Go back to your project folder using the command window once there you can execute:karma init
Just hit enter until it finishes; bottom line this will create a file named: karma.config.js
In my project this file looks like this, yours probably will include some helpful comments on the different settings:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'../app/*.js',
'../app/lib/angular.js',
'../app/lib/angular-route.min.js',
'../app/lib/angular-mocks.js',
'../app/app.js',
'controllers/*.js',
'services/*.js',
],
exclude: [
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome','Firefox'],
captureTimeout: 60000,
singleRun: false
});
};
Important: make sure you included angular-mocks in your configuration, the inject function is on that module.
5. Go back to your command window, navigate where your karma.config.js file is and and execute: karma start
At this point you will be good to go to start writing tests with jasmine.
a simple jasmine test for your controller will be:
describe('MainCtrl', function() {
var $scope, $rootScope, createController;
beforeEach(inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
var $controller = $injector.get('$controller');
createController = function() {
return $controller('MainCtrl', {
'$scope': $scope
});
};
}));
it('should have a...', function() {
var controller = createController();
// do your testing here...
});
});

Resources