ngStorage breaking my application tests - angularjs

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

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.

Uncaught Error: Mismatched anonymous define() module: function in karma and jasmine unit testing with requirejs [duplicate]

This question already has answers here:
Getting "Mismatched anonymous define() module..." when I try running tests
(2 answers)
Closed 5 years ago.
I am trying to run unit test cases for my controllers, I have tried the following but getting the below error, please let me know to run this test successfully. Thanks in advance.
spec.js:
describe('MainCtrl', function() {
beforeEach(module('app-module'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('$scope.titleofapp', function() {
var $scope, controller;
beforeEach(function() {
$scope = {};
controller = $controller('MainCtrl', { $scope: $scope });
});
it('sets the title of app to "app-module" module', function() {
$scope.titleofapp();
expect($scope.title).toEqual('My Test App !');
});
});
});
app.js:
define(['angular', './app-module'], function(angular, appModule) {
'use strict';
return appModule.controller('MainCtrl', ['$http', '$q', 'appService', '$stateParams', function($http, $q, $stateParams, appService){
$scope.titleofapp = function(){
$scope.title = 'My Test App !';}
}]);
});
Below is my karma.conf.js file configuration:
karma.conf.js:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine','requirejs'],
files: [
'node_modules/requirejs/require.js',
'node_modules/karma-requirejs/lib/adapter.js',
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'public/app/app.js',
'public/tests/spec.js'
],
exclude: [
],
plugins: [
'karma-requirejs',
'karma-chrome-launcher',
'karma-jasmine'
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
I have configured requirejs like above and getting the below error now:
Error:
Uncaught Error: Mismatched anonymous define() module: function (angular, appModule) {
'use strict';
return appModule.controller('MainCtrl', ['$http', '$q', 'appService', '$stateParams', function($http, $q, $stateParams, appService){
$scope.titleofapp = function(){
$scope.title = 'My Test App !';}
}]);
}
http://requirejs.org/docs/errors.html#mismatch
at node_modules/requirejs/require.js:165
Here is your karma.conf.js file I've edited to make possible run with RequireJS. Comments styled as // -- mostly (except when trailing) the stuff that I commented out, and styled as /* */ -- are real comments about what's the purpose of specific line presence or absence. I hope all that commenting will help to understand what's going on.
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine','requirejs'],
files: [
/* not needed because you've told to use requirejs higher in frameworks */
// 'node_modules/requirejs/require.js',
/* i assume this one in no need in your case but could be yes */
// 'node_modules/karma-requirejs/lib/adapter.js',
/* as far as i understand angular.js is amd loadable so don't load it directly */
// 'node_modules/angular/angular.js',
/* i am not sure about this one and how it should be launched so commented it out for now */
// 'node_modules/angular-mocks/angular-mocks.js',
/* will be loaded by tests*/
// 'public/app/app.js',
/* tests should not be loaded directly eigther */
// 'public/tests/spec.js'
/* now configure karma with what will be servable */
{pattern: 'node_modules/**/*.js', included: false}, // all stuff from what npm installed
{pattern: 'src/**/*.js', included: false}, // your source filed
{pattern: 'tests/**/*Test.js', included: false}, // your tests or specs
/* this is the only file to be loaded directly */
'tests/test-main.js' // karma will load this file and it will do all the stuff
],
exclude: [
],
/* karma will load all sibling npm modules with name karma-* so these lines not needed i believe */
// plugins: [
// 'karma-requirejs',
// 'karma-chrome-launcher',
// 'karma-jasmine'
// ],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
Then here I made a sample code for main-test.js file.
var allTestFiles = [];
var TEST_REGEXP = /base\/tests\/.*(spec|test)\.js$/i;
// Get a list of all the test files to include
/* as far as i remember window.__karma__.files contains array of all servable files */
Object.keys(window.__karma__.files).forEach(function (file) {
//console.log('original path', file);
if (TEST_REGEXP.test(file)) {
/* below i commented out file path modification suggested at http://karma-runner.github.io/1.0/plus/requirejs.html
* personally i never needed that. Your case might be different so you can play around with this part
*/
var normalizedTestModule = file;//'/base/' + file.replace(/^\/base\/|\.js$/g, '')
//console.log('normalized path', normalizedTestModule);
allTestFiles.push(normalizedTestModule);
}
});
//console.log(allTestFiles); // list all test filed that will be run
/* now confifure requirejs so it could do the job
* for more details please visit http://requirejs.org/docs/api.html#config
*/
require.config({
// Karma serves files under /base, which is the basePath from your config file
/* i prefer this to be default */
baseUrl: '/base/src',
paths: {
/* could be this to do stuff like
* define(['node_modules/cool-module/module.js], function(Module){
*
* });
*/
node_modules: '/base/node_modules',
/* below is just examples that what it could be if you needed those */
// jquery: '/base/node_modules/jquery/dist/jquery',
// underscore: '/base/node_modules/underscore/underscore',
// backbone: '/base/node_modules/backbone/backbone',
// text: '/base/node_modules/requirejs-text/text',
// templates: '/base/src/templates'
},
/* Dynamically load all test files
* An array of dependencies to load. Useful when require is defined as a
* config object before require.js is loaded, and you want to specify
* dependencies to load as soon as require() is defined. Using deps
* is just like doing a require([]) call, but done as soon as the loader
* has processed the configuration. It does not block any other require()
* calls from starting their requests for modules, it is just a way to
* specify some modules to load asynchronously as part of a config block.
* (http://requirejs.org/docs/api.html#config-deps)
*/
deps: allTestFiles,
/* A function to execute after deps have been loaded. Useful when require
* is defined as a config object before require.js is loaded, and you want
* to specify a function to require after the configuration's deps array
* has been loaded.
* http://requirejs.org/docs/api.html#config-callback
* Could be as simple as
* callback: window.__karma__.start
* but i do it via additional wrapper so i can require something specific
* for the whole test suite (like jasmine-jquery), you will the sample below
*/
callback: startTestWithJasmineJquery
});
function startTestWithJasmineJquery(){
require(['node_modules/jasmine-jquery/lib/jasmine-jquery'], function(){
/* now jasmine-jquery is loaded and its features are available
* so we can window.__karma__.start -- it will actually run tests
*/
window.__karma__.start();
});
}
Please note that all config options assume folder and some specific files structure as:
node_modules/
src/
tests/
test-main.js
karma-conf.js
Please also note again that this is very basic config I've provided and there might be some specific stuff relative to angular or your project logic and needs and thus there might be some (or many) changes to be made.

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.

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'

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.

Resources