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.
Related
I've tried several tutorials and looked at many of the solutions provided here. I am new to Angular and currently trying to set up testing for a rather big SPA.
Following this tutorial I have completed:
Angularjs application setup
Karma setup
Our first test
The karma config file is basically the default content, with some references in files and exclude:
// list of files/patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/app.js',
'JavaScript.spec.js'
],
I reinstalled the entire test implementation and now the simple test works again. But trying to write a test for a controller does not work:
here is the error message
I changed the path referencing the bower_components and app files in the karma config file. Now the shell running karma returns an error message from the app.js file, saying:
Uncaught ReferenceError: Logging is not defined
Writing a test identical to the one from doucmentation, gives the following error:
Here is the test code:
describe('nyKladdController', function () {
beforeEach(module('app'));
var $controller;
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
}));
describe('$scope.mixTable', function () {
it('is false', function () {
var $scope = {};
var controller = $controller('nyKladdController', { $scope: $scope });
expect($scope.mixTable).toBeFalsy();
});
});
});
As you can see from the error message: after the app module, the test file start loading the app dependencies. Here is the app.js file:
(function () {
'use strict';
angular.module('app', [
'ngAnimate', 'ngRoute', 'ngSanitize', 'ngResource', 'ngMessages',
'AdalAngular', 'config', 'angular.filter',
'ui.bootstrap', 'ui.mask', 'ui.select', 'ui.validate',
'angular-loading-bar', 'ui.tree', 'ui.tree-filter', 'checklist-model'
]);
})();
In other words: how can i get my tests to load the app dependecies as well.
I had to load in all the app dependencies from app.js in to karma.config file. Now the files array in karma config looks like this:
// list of files / patterns to load in the browser
files: [
//bower modules
'./bower_components/angular/angular.js',
'./bower_components/angular-mocks/angular-mocks.js',
'./bower_components/angular-ui-mask/src/mask.js',
'./bower_components/angular-ui-select/dist/select.js',
'./bower_components/angular-ui-tree-filter/dist/angular-ui-tree-filter.js',
'./bower_components/angular-ui-tree/dist/angular-ui-tree.js',
'./bower_components/angular-ui-validate/dist/validate.js',
'./bower_components/angular-loading-bar/build/loading-bar.js',
// node modules
'./node_modules/angular-animate/angular-animate.js',
'./node_modules/angular-route/angular-route.js',
'./node_modules/angular-sanitize/angular-sanitize.js',
'./node_modules/angular-resource/angular-resource.js',
'./node_modules/angular-messages/angular-messages.js',
'./node_modules/adal-angular/dist/adal-angular.min.js',
'./node_modules/angular-filter/dist/angular-filter.js',
'./node_modules/angular-ui-bootstrap/dist/ui-bootstrap.js',
'./node_modules/bower-config/lib/Config.js',
'./node_modules/checklist-model/checklist-model.js',
//app file
'./app/app.js',
'./app/common/config/config.js',
//test files etc..
'JavaScript.spec.js',
'./app/produkt/ny/controllers/*.js' // tester å hente inn controller som refereres i test filen
],
This may be because Karma is loading the source files in the wrong order. For Angular to work properly, each module must be loaded before any component, services, etc. associated with that module.
To fix this, you can change your Karma configuration to ensure your module files are loaded first.
// list of files / patterns to load in the browser
files: [
'../../bower_components/angular/angular.js',
'../../bower_components/angular-mocks/angular-mocks.js',
'app/**/*.module.js',
'app/**/*.js'
],
This is assuming you're using some kind of naming convention for angular modules (like *.module.js as in the above example). Otherwise you'll have to list the paths to the modules individually.
add beforeEach(module("your-module-name")); => your angular application name from app.js"
describe('check a controller', function () {
beforeEach(module("your module name")); // I think you missed this.
var scope, checkController;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.new();
checkController = function () {
return $controller('nyKladdController', {
'$scope': scope
});
};
}));
it('has a dummy spec to test 2 + 2', function () {
// An intentionally failing test. No code within expect() will never equal 4.
expect(2 + 2).toEqual(4);
});
});
karma.conf
files: [ // sample order. Include your files accordingly
'src/bower_components/angular/angular.min.js',
'src/bower_components/angular-mocks/angular-mocks.js',
// some sample libraries
'src/bower_components/angular-cookies/angular-cookies.min.js',
'src/bower_components/angular-ui-router/release/angular-ui-router.min.js',
'src/bower_components/angular-resource/angular-resource.min.js',
'src/bower_components/angular-sanitize/angular-sanitize.min.js',
'src/bower_components/angular-loading-bar/build/loading-bar.min.js',
'src/app/app.js',
'src/app/**/*.js',
'tests/unit/**/*.spec.js'
],
exclude: []
I am currently working on writing a simple test case for the driver script using IIFE(Immediately invoked function expression). Here is my driver script.
driver.js
(function() {
"use strict";
var app = angular
.module("myApp", [
"ui.bootstrap",
"ui.sortable"
]);
}());
Here is my spec driver.spec.js
describe("application configuration tool driver", function() {
it("should create an angular module named myTest", function() {
expect(app).toEqual(angular.module("myApp"));
});
});
When I run my spec using IIFE. I am getting a ReferenceError: app is not defined.
If I run the driver script without IIFE:
var app = angular
.module("myApp", [
"ui.bootstrap",
"ui.sortable"
]);
My spec passes. Any thoughts on passing the spec using IIFE?
You can move app back to the outer scope (if that's an option you can take, of course):
var app;
(function(app) {
"use strict";
app = angular
.module("myApp", [
"ui.bootstrap",
"ui.sortable"
]);
}(app));
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).
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.
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.