Testing AngularJS using Jasmine - angularjs

I'm trying to test my angular project and keep falling at the first hurdle. By just instantiating my module without even testing anything karma is throwing an error.
If I do include an it statement karma gives me an error saying 'Error: [$injector:modulerr]'. I'm using ngRoute in my project and I'm wondering if that has anything to do with it.
Here's my code, any suggestions on what could be wrong would be much appreciated.
angular.module('MyApp', ['ngRoute'])
.controller('HomeCtrl', ['loadArtists', function(loadArtists){
var self = this;
self.homeArtistsArray = [];
self.homeArtistsArray = loadArtists;
}])
-
describe('Practice', function(){
beforeEach(module('MyApp'));
var ctrl;
beforeEach(inject(function($controller){
ctrl = $controller('HomeCtrl');
}))
it('should do nothing',function(){
})
});
-
files: [
'jquery-1.11.3.min.js',
'angular.js',
'angular-mocks.js',
'js/app.js',
'js/appControllers.js',
'js/appFactory.js',
'js/testFile.js'
],
If ngRoute is the problem could you suggest somewhere to download it from.

You need to add angular-route.js to your karma configuration.
BTW, when debugging, you should use the not-minified angular.js file, so you get a full debug message with the error (here, modulerr).

Related

RestAngular - Injector module error

I'm totally new to the Restangular and trying to learn it by implementing a simple application by calling a webapi. I'm able to call this service with simple $http service and getting the correct response.
The code I have written is as below.
I have googled the issue to find the solution but no like.
var myApp = angular.module('myApp', ['restangular']);
myApp.config(function (RestangularProvider) {
var newBaseUrl = "";
newBaseUrl = 'http://localhost:37103/api/'
RestangularProvider.setBaseUrl(newBaseUrl);
})
myApp.controller("myCtrl", function ($scope, Restangular) {
$scope.data = "Default Value"
$scope.data = Restangular.one("employee").get();
})
The error which I'm getting on chromes console is as below
angular.min.js:6 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=myApp&p1=Error%3A%2…0Bc%20(http%3A%2F%2Flocalhost%3A37103%2FSource%2Fangular.min.js%3A21%3A179)
The above error is clickable and it says may be the file is mot included. But I have included the restangular.js file and I could see it getting loaded in the network tab.
Thanks!
For this issue I found something was wrong in the restangular.js file which I downloaded. I replaced it with the cdn tag cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular‌​.js and it worked. Its very strange.

AngularJS Unit Test Error dependence

I create a very small project to test the unit test in AngularJS. The test work until I try to include the dependence restangular. Why it generates conflicts?. Files:
karma.conf.js
files: [
'lib/angular.js',
'lib/angular-route.js',
'lib/angular-mocks.js',
'lib/angular-cookies.js',
'lib/angular-md5.js',
'lib/restangular.js',
'app.js',
'tests/app.spec.js'
]
app.js
var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'ngCookies',
'angular-md5',
'restangular' //This generate ERROR!
]);
app.spec.js
describe('PhoneListController', function() {
beforeEach(module('phonecatApp'));
beforeEach(module('ngRoute'));
beforeEach(module('angular-md5'));
beforeEach(module('restangular')); //This generate ERROR!
it('should...', inject(function($controller) {
var scope = {};
var ctrl = $controller('PhoneListController', {$scope: scope});
expect(scope.phones.length).toBe(3);
}));
When you trying to load restangular. Then you might be getting error like
Faild to instantiate module restangular due to (_'underscore.js') is undefined. The '_'(undescore) javascript utility library that Restangular uses and depending on it. Include (_'underscore.js') library before the angular js in your template.
Here is your working jsfiddle code please take a look http://jsfiddle.net/chhitij92/x67u4Ldu/ In external resource I Included '_'(undescore) cdn after this its working.

Grunt js uglify fails - console Error: Unknown provider: aProvider <- a

Im pretty new and trying to build a app Its working fine
Now I am trying to minify the files:
Error: Unknown provider: aProvider <- a
uglify: {
my_target: {
files: {
'app/output/output.js': [
'app/js/angular-ui-router.js',
'app/js/angular-animate.js',
'app/js/packery.pkgd.js',
'app/js/app.js',
'app/js/services.js',
'app/js/controllers.js',
'app/js/directives.js'
]
}
}
}
1) How to solve this problem?
2) Some of blog examples suggesting to use grunt-contrib-concat before uglify use - why?
Second question is confusing me
Edit:
After read about ng-annotate
They Must be written using the array syntax.
My code strcture like this
var app = angular.module('bigApp', []);
app.controller('mainController', ['$scope', function($scope) {
$scope.message = 'HOORAY!';
}]);
But didnt solve error 'Unknown provider: aProvider <- a'
The files should be concatenated before you uglify them and the reason why is that uglify will change names of functions, controllers and so on, when you do it like in your example the files will be uglified out of context of the whole application and renamed functions cant be found properly. And to uglify Angularjs properly you should have ng-annotate in grunt as well, unless you already use following notation in controllers/services/factories
need ng-annotate
.controller('myController', function (serviceA, factoryB, filterC){
//something fancy
})
dont need ng-annotate
.controller('myController', [ 'serviceA', 'factoryB', 'filterC', function (serviceA, factoryB, filterC){
//something fancy
}])

Writing Unit Testing With Jasmine , Require JS in Karma for Angular JS?

I have Done a Library Management App with Angular JS and Mongo Lab will Act as a DB Part, I am facing issuse with Require JS Dependency While Crating Unit test Case
Error: [$injector:modulerr] Failed to instantiate module lmaApp due to:
Error: [$injector:nomod] Module 'lmaApp' is not available!
The Above error I am facing,kindly help me to get out from this.
MyCode:
Controller.js
define(
['modules'],
function(lmaApp) {
lmaApp.controller('gridControl',['$scope' , '$http' , 'internal' , 'commonValues', function($scope , $http , internalFn , commonValues){
jQuery('ul.navbar-nav li').removeClass('active');
jQuery('ul.navbar-nav li:nth-child(1)').addClass('active');
$('.loaderImg').removeClass('no-loading');
var lmaTableData = internalFn.getTableData(commonValues.mongoAPIurl,commonValues.bookTableName,'');
var promise = lmaTableData
.success(function(tbData) {
if(tbData.length > 0){
$scope.nobook=0;
$scope.books =tbData;
}
else{
$scope.nobook =1;
}
}).then(function (response) {$('.loaderImg').addClass('no-loading');});
}]);
});
modules.js
define(
['app_config','angularRoute'],
function() {
var lmaApp =angular.module('lmaApp',['ngRoute'])
return lmaApp;
});
app_config.js
define(
['angular','angularRoute','modules'],
function() {
angular.element(document).ready(function() {
angular.bootstrap(document, ['lmaApp'], {});
});
});
My spec File
controllerSpec.js
define(['angular', 'angular-mocks'], function() {
describe('gridControl', function(){
beforeEach(module('lmaApp'));
it('should get the book table Datas', inject(function($controller) {
var scope = {},
ctrl = $controller('gridControl', {$scope:scope});
expect(scope.phones.length).not.toEqual(0);
}));
});
});
Here i have a doubt with require js dependecy like i have to mention modules.js as a dependency in Spec file too.
Your controller-spec.js is wrong, you need to call its dependencies which is your module.js, app_config.js, Controller.js also 'angularRoute'. In other ot make your app to able to boostrap.
try it like this
define(['angular', 'angular-mocks','modules', 'app_config', 'Controller', 'angularRoute'], function() { ... }
Still I have nothing to be sure that it will work for you. Because if any of your configuration is wrong. It will be broken. Using requireJS with AngularJS in unit testing is very tricky/complex in the configuration.
You should read more about requireJS config, and using shim for define dependencies for your script. It will be lots clearer and eaiser to handle when your app getting bigger. For example you can do something like this in your config file:
shim: {
'modules': ['angular', 'app_config', 'angular-mocks'],
'app_config': ['angular', 'angularRoute', 'modules'],
'Controller': ['modules']
}
and your controller-spec.js will be like this
define(['modules', 'app_config', 'Controller'], function(){ ... });
Also Bootstraping angular on element ready is not a good idea for testing. It may cause some conflict in loading simulating of karma. I am not sure but don't feel right about it
Sencond Your app_config.js and modules.js are dependency of each other. So what do you think if there's something require an order in loading. Which will need to load first? since Both required the other to be loaded before it got to be injeacted by requireJS.
Still I don't think my solution will work. Because your config seem so wrong.

angular mock `module` resulting in '[Object object] is not a function'

I'm trying to create some unit tests in Angular using Jasmine being run through Teaspoon. The tests are running, however I have a simple test just to test the existence of a controller that is failing. I have the following test setup.
//= require spec_helper
require("angular");
require("angular-mocks");
var app = require("./app");
describe("My App", function() {
describe("App Controllers", function() {
beforeEach(module("app"))
it("Should have created an application controller", inject(function($rootScope, $controller){
var scope = $rootScope.$new();
ctrl = $controller("ApplicationCtrl", { $scope: scope });
}));
})
})
The require statements are processed by Browserify which is handling my dependencies, but I can also hook into sprockets which I'm using for the spec helper.
Inside the app that is being required, I have
require("angular");
var controllers = require("./controllers");
var app = angular.module("app", [
"app.controllers"
]);
exports.app = app;
When I run this test, I get the following error produced
Failure/Error: TypeError: '[object Object]' is not a function (evaluating 'module("aialerts")')
I've spent quite a while trying to figure this out but I have no idea what's going on. Any help appreciated.
I had the same problem. Change this line:
beforeEach(module("app"))
to:
beforeEach(angular.mock.module("app"))
Browserify uses Node-style require, where module is an object that you can use to export functionality:
console.log(module); // {exports: {}}
angular-mocks.js tries to attach a function to window.module, but that's not possible in Browserify/Node.
Taking a look through the angular-mocks source, it appears that angular-mocks also attaches the module function to angular.mock. So instead of using the global module object, you must use angular.mock.module.

Resources