How to inject External Providers in karma jasmine test case? - angularjs

I'm new to Angular and karma test cases.
For my application I'm using Angularjs and SweetAlert for displaying alerts. ( SweetAlert Plugin here )
Below is my code for getting the status for the http request and I display the http request status in SweetAlert
(function () {
'use strict';
angular
.module('app.admin')
.controller('TestController', TestController);
TestController.$inject = ['$scope','$http','SweetAlert'];
function TestController($scope,$http,SweetAlert) {
var vm = this;
vm.test = 'hi';
vm.todos = [];
vm.todo = 'Run';
vm.status = '';
vm.GetURL = function(){
$http.get("some url")
.then(function (result) {
vm.status = result.status;
SweetAlert.swal(JSON.stringify(vm.status))
});
};
vm.addTodo = function(){
vm.todos.push(vm.todo);
};
vm.removeTodo = function(index){
vm.todos.splice(index, 1);
};
}
})();
This is working fine without any problems, but I need to test my application, for that I am using karma with jasmine framework. Below is my karma.config.js and test file.
karma.config.js
// 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',
'bower_components/sweetalert/dist/sweetalert.css',
'bower_components/sweetalert/dist/sweetalert.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'../app/js/app.js',
'test/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: 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'
],
// 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
})
}
test.spec.js
'use strict';
describe('Test Controller', function () {
// load the controller's module
var MainCtrl,
SweetAlert,
URLService,
httpcall,
scope;
beforeEach(module('sample'));
/*beforeEach(inject(function(_SweetAlert_,_URLService_){
URLService = _URLService_;
SweetAlert = _SweetAlert_;
}));*/
// Initialize the controller and a mock scope
beforeEach(inject(function ($rootScope, $controller,$http,_SweetAlert_) {
scope = $rootScope.$new();
MainCtrl = $controller('TestController', {
$scope: scope,
httpcall : $http,
SweetAlert : _SweetAlert_
});
}));
it('should tell hi', function () {
expect(MainCtrl.test).toBe("hi");
});
it('should give the status', function () {
MainCtrl.GetURL();
expect(MainCtrl.status).toBe(200);
});
it('should have no items to start', function () {
expect(MainCtrl.todos.length).toBe(0);
});
it('should add items to the list', function () {
MainCtrl.todo = 'Test 1';
MainCtrl.addTodo();
expect(MainCtrl.todos.length).toBe(1);
});
it('should add then remove an item from the list', function () {
MainCtrl.todo = 'Test 1';
MainCtrl.addTodo();
MainCtrl.removeTodo(0);
expect(MainCtrl.todos.length).toBe(0);
});
});
But it throws the following error:
F:\Projects\Angular\NewSample\Development\test\master>gulp test
[13:06:40] Using gulpfile F:\Projects\Angular\NewSample\Development\test\master\gulpfile.js
[13:06:40] Starting 'test'...
WARN `start` method is deprecated since 0.13. It will be removed in 0.14. Please
use
server = new Server(config, [done])
server.start()
instead.
27 01 2016 13:06:40.250:INFO [karma]: Karma v0.13.19 server started at http://lo
calhost:9876/
27 01 2016 13:06:40.261:INFO [launcher]: Starting browser Chrome
27 01 2016 13:06:41.793:INFO [Chrome 47.0.2526 (Windows 8.1 0.0.0)]: Connected o
n socket /#hmyJFO5x2TLTkMMHAAAA with id 83740230
Chrome 47.0.2526 (Windows 8.1 0.0.0) LOG: 'localhost'
Chrome 47.0.2526 (Windows 8.1 0.0.0) LOG: 'localhost'
Chrome 47.0.2526 (Windows 8.1 0.0.0) Test Controller should tell hi FAILED
Error: [$injector:unpr] Unknown provider: SweetAlertProvider <- SweetAle
rt
http://errors.angularjs.org/1.4.2/$injector/unpr?p0=SweetAlertProvider%2
0%3C-%20SweetAlert
at F:/Projects/Angular/NewSample/Development/test/ap
p/js/base.js:9274:12
I don't know why., How can i solve this?
For this i take long week, is it possible to include third party plugins in karma.
Please help me, Thanks in advance.

Before inject you should add this line.
beforeEach(module('_SweetAlert_'));
And also change karma.config.js file path like below.
bower_components/sweetalert/dist/sweetalert.min.js to app/bower_components/sweetalert/dist/sweetalert.min.js

Try this.(Here I have used $injector to inject the SweetAlert)
describe('Test Controller', function () {
var MainCtrl,
SweetAlert,
URLService,
httpcall,
scope;
beforeEach(module('sample'));
beforeEach(module('SweetAlert'));
beforeEach(inject(function ($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
SweetAlert = $injector.get('SweetAlert');
MainCtrl = $controller('TestController', {
$scope: scope,
httpcall : $http,
SweetAlert : SweetAlert
});
}));
});

Related

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR SyntaxError: Invalid character: '#'

i'm new in testing a angular test so i need hand for a professional out there
i use karma, jasmine and phantomjs i just follow the video tuts
so i finish the config and i try my test
here my karma congif
// Karma configuration
// Generated on Fri Feb 24 2017 09:59:10 GMT+0800 (PHT)
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',
'../app/caes/controllers/positions/PositionIndexCtrl.coffee',
'unit/*.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,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
my unit test testingPositionCtrlSpec.js
describe('Testing Position Suite', function () {
describe('Testing Position Controller',function () {
it('Should initialize the position in the scope ', function () {
module('CaesApp');
var scope = {};
var ctrl;
inject(function ($controller) {
ctrl = $controller('PositionIndexCtrl', {$scope:scope})
});
expect($scope.position).toBeDefine();
});
});
});
this is the controller i test PositionIndexCtrl.coffee
#= require ./../../module
PositionIndexCtrl = ($scope, $resource, $route, $mdDialog, Position)->
#positions = Position::list.query()
#showNew = (ev)->
position = new Position()
$mdDialog.show
controller: "PositionNewDialogCtrl"
templateUrl: '/templates/positions/new'
parent: angular.element(document.body)
targetEvent: ev
clickOutsideToClose:true
fullscreen: #customFullscreen
locals:
position: position
$scope.edit = (rowId) ->
position = Position.get(id: rowId)
$mdDialog.show
controller: "PositionEditDialogCtrl"
templateUrl: '/templates/positions/edit'
parent: angular.element(document.body)
clickOutsideToClose:true
fullscreen: #customFullscreen
locals:
position: position
$scope.delete = (rowId) ->
Position.get { id: rowId }, (position) ->
confirm = $mdDialog.confirm().title('Would you like to delete '+ position.name + ' Position').targetEvent(rowId).ok('Yes!').cancel('Cancel')
$mdDialog.show(confirm).then (->
position.$remove ->
console.log('Deleted Success!')
$route.reload()
)
return
PositionIndexCtrl.$inject = ["$scope", "$resource", "$route", "$mdDialog", "Position"]
angular
.module "CaesApp"
.controller "PositionIndexCtrl", PositionIndexCtrl
my error in terminal
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
SyntaxError: Invalid character: '#'
at /Users/cdasia-tsd/Desktop/revampCAES/app/assets/javascripts/app/caes/controllers/positions/PositionIndexCtrl.coffee:1
i dont know why he consider '#' a error?
my hypothesis
he cant read coffeescript??
i need to declare #require to my unit test?
if someone experience this please share your knowledge
You have to compile your coffescript into JavaScript before karma can run it. Karma can't run coffescript, nothing runs coffescript directly, it's always compiled into JavaScript.
You can use https://github.com/karma-runner/karma-coffee-preprocessor

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.

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

Unit testing using Jasmine and Karma / AngularJS project

I am writing test cases using AngularJS with Jamsine. Working on mobile application using AngularJS and for UI using IONIC framework. So I am calling one of controller function from my spec.js for testing. Meantime, I am getting error like.
Error: Unexpected request: GET ./partials/main.html
No more request exceepted
This is my mail html file. In main.html file we are loading all other states of application.
And I already injected html in spec.js. See below code.
beforeEach(inject(function ($rootScope, $controller, $q,$injector) {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET('./partials/main.html').respond(200, '');
}));
Still i ma not able to resolve error. Can i add those html files in 'spec.js' ? or any other solution ? Please help me. I am a fresher with Karma and Jasmine.
Thanks in advance.
Change your code to expectGET in place of whenGET like this
beforeEach(inject(function ($rootScope, $controller, $q,$injector) {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.expectGET('./partials/main.html').respond(200);
}));
Yes Keshav. Please see below code :
Below is my karma.conf.js file. Here are all files added which I need to test. And as well as I have added a few plugins for generating reports and code coverage.
module.exports = function(config) {
config.set({
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
plugins: [
'karma-jasmine',
'karma-coverage',
'karma-chrome-launcher',
'karma-html-reporter',
'karma-ng-html2js-preprocessor'
],
// list of files / patterns to load in the browser
files: [
'my_dir_path/www/js/libs/angular.js',
'my_dir_path/www/js/libs/angular-mocks.js',
'my_dir_path/www/js/libs/ionic.js',
'my_dir_path/www/js/libs/angular.min.js',
'my_dir_path/www/js/libs/angular-route.js',
'my_dir_path/www/js/libs/angular-sanitize.js',
'my_dir_path/www/js/libs/angular-animate.js',
'my_dir_path/www/js/libs/angular-touch.min.js',
'my_dir_path/www/js/libs/angular-ui-router.js',
'my_dir_path/www/js/libs/ionic-angular.js',
'my_dir_path/www/js/libs/http-auth-interceptor.js',
'my_dir_path/www/js/libs/ng-map.min.js',
'my_dir_path/www/js/index.js',
'my_dir_path/www/js/app.js',
'my_dir_path/www/js/controllers.js',
'my_dir_path/www/js/services.js',
'my_dir_path/www/js/startSpec.js',
'*.html'
],
// 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: {
//'**/*.html': ['angular-templating-html2js']
"my_dir_path/www/partials/*.html": ["ng-html2js"]
},
ngHtml2JsPreprocessor: {
// If your build process changes the path to your templates,
// use stripPrefix and prependPrefix to adjust it.
//stripPrefix: "source/path/to/templates/.*/",
//prependPrefix: "web/path/to/templates/",
stripPrefix:"my_dir_path/www/",
// the name of the Angular module to create
moduleName: 'partials'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'html'],
// the default configuration
/* htmlReporter: {
outputDir: 'karma_html',
templatePath: 'node_modules/karma-html-reporter/jasmine_template.html'
}, */
// 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
});
};
And this is my spec.js file. Here I am writing unit test cases for the controller. In this specs calling function "$scope.onClickResetForgot()" (That is in controller) for testing controller code. In controller I am also calling one HTTP service. After HTTP call, we are not able to back in response that why we have updating scope manually via $scope.$digest().
'use strict';
describe('loginController', function () {
var $scope,$controller,$httpBackend, AuthenticationService, def, respData = {data : {Success:true,ErrorMsg:""}};
beforeEach(inject(function ($rootScope, $controller, $q,$injector) {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.expectGET('./partials/main.html').respond(200);
AuthenticationService = {
forgotPassword: function (data) {
console.log(data);
def = $q.defer();
return def.promise;
}
};
spyOn(AuthenticationService, 'forgotPassword').and.callThrough();
$scope = $rootScope.$new();
$controller = $controller('loginController', {
'$scope': $scope,
AuthenticationService : AuthenticationService
});
}));
it("Verifying login credentials, device token and device id." , function() {
$scope.Reset.Email = "harish.patidar#gmail.com";
$scope.onClickResetForgot();
def.resolve(respData);
// Update response to controller. So we need to call below line manually.
$scope.$digest();
expect(AuthenticationService.forgotPassword).toHaveBeenCalled();
$httpBackend.flush();
})
});
});
And this is my controller in controller.js.
.controller('loginController', ['$rootScope', '$scope', '$http', '$state', 'AuthenticationService', '$ionicPopup', function($rootScope, $scope, $http, $state, AuthenticationService,$ionicPopup) {
$scope.onClickResetForgot =function(type) {
console.log($scope.Reset.Email);
$scope.forgotMessage = "";
$rootScope.message = "";
AuthenticationService.forgotPassword({"Email": $scope.Reset.Email}).then(function (resp) {
var forgotPasswordPopup = $ionicPopup.alert({
title: "Forgot Password",
template: "An email has been sent to '"+$scope.Reset.Email+"' with instructions for recovering your AlertSense credentials"
});
forgotPasswordPopup.then(function(res) {
$scope.onCancelForgot();
});
});
}
}])
So after updating scope to controller, I am getting error as mentioned above. Please let me know if you need more information.

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