I have an angular 1.5 project with many modules and each module may depend on other modules. Trying to unit test say a controller which is part of a module I would do import the module like this:
angular.mock.module('SaidModule');
...then provide and inject its services where needed.
The problem is that SaidModule depends on AnotherModule1, AnotherModule2, AnotherModule3....
angular.module('SaidModule', ['AnotherModule1', 'AnotherModule2', 'AnotherModule3']);
So naturally when I call SaidModule the other modules are also invoked which is out of scope in terms of Unit testing
In the unit test I have tried the following solution
angular.module('AnotherModule1',[]);
angular.module('AnotherModule2',[]);
angular.module('AnotherModule3',[]);
angular.mock.module('SaidModule');
and although for the current unit test I have successfully decoupled the dependencies I have also destroyed
the actual AnotherModule1, AnotherModule2, AnotherModule3 so when its there turn to be unit tested they are
not even visible in the angular project which seems correct to me. as I am using angular.module to define a
new module which just happens to override the actual module.
This solution though is also suggested here mocking module dependencies
In the angular docs it states see angular docs mock module
If an object literal is passed each key-value pair will be registered on the module via $provide.value,
the key being the string name (or token) to associate with the value on the injector.
So it seems to me that the solution is using somehow angular.mock.module somehow to override the dependent
modules but so far I have not found a solution.
Any help much appreciated
By calling angular.module('AnotherModule1',[]) you are redefining the AnotherModule1, which I think is causing your downstream problems. Instead, use $provide for each dependent service. There's no need to mock the dependent modules.
Let's say your controller definition looks like this:
angular
.module('SaidModule', ['AnotherModule1', 'AnotherModule2'])
.controller('SaidController', [
'$scope',
'AnotherService',
function($scope, AnotherService) {
this.anotherService = AnotherService.helper();
}
);
Then your test might look like:
describe('SaidController', function() {
var controller, scope, AnotherService;
beforeEach(module('SaidModule'));
beforeEach(module(function($provide) {
AnotherService = { helper: function() { return 0; } };
$provide.value('AnotherService', AnotherService);
}));
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
controller = $controller('SaidController', {
$scope: scope
});
}));
it('creates controller', function() {
expect(controller).not.toBeNull();
});
});
There's no need to mock the dependent modules, just the dependent services.
Related
Suppose that I have an SPA written via AngularJS 1.x.
It has a single app module defined like this:
var app = angular.module('app', ['ngAlertify', 'ngRoute', 'ui.bootstrap'])
I also have several controllers which are defined in separate *Ctrl.js-files. What is the appropriate way to define them?
I see two options here. The first one is
app.controller('LoginCtrl', function($scope) { /* ... */ });
and the second one is
angular.module('app').controller('LoginCtrl', function($scope) { /* ... */ });
Which one is better and most common-used practice? Is there any downsides of using either of them?
If I understand your question correctly then you wan to know different between
app.controller('LoginCtrl', function($scope) { /* ... */ });
vs
angular.module('app').controller('LoginCtrl', function($scope) { /* ... */ });
In above two in first method app is a global object which you declared somewhere i.e. in app.js like
var app = angular.module('app',[]);
In this case app is a global variable which will be accessible throughout your entire application. which I believe is not a good thing to use global variable
in our application.
In second method we are using global angular object to create a controller so that in this we will not be using global variable. In this case app.js will look like
(function(){
'use strict';
var app = angular.module('app', []);
....
....
....
....
})
In this case app variable will not be available anywhere apart from this file.
So I belive second method is better than first one.
My personal preference is to use app.controller('LoginCtrl', function($scope) { /* ... */ }); as this makes it easier to reuse the controller in another project with little to no changes, without those annoying module not found errors because you forgot to rename the module when reusing the file
I think that depends a bit on the personal style of writing. One thing is that while working with AngularJS 1.x.x you can have different styles of writing code, method stacking etc.
Personally, I prefer app.controller('LoginCtrl', function($scope) { /* ... */ }); mainly because you can easily preview your controller and distinguish it from thge module. Another bonus I see of having a clearly defined separate module is that you can easily check what includes you have ('ngAlertify', 'ngRoute', 'ui.bootstrap').
Most commonly used as far I have seen, even here on SO, is the method that I previously mentioned. Yet again this is something that is more reflective of personal style rather than strong pre-requirements of writing code. I hope that helps to some extend.
None of the above. The purpose of modules is to keep the application modular and not pollute global scope.
You can have var app = ... but this should be done inside IIFE once per file.
Another issue with modules is the precedence. If the application uses angular.module('app') module getter, the files should be loaded in specific order, in order for the module to be defined when it is retrieved in other files. This creates problems if they aren't, for example when they are concatenated in alphabetic order.
The solution is to use one module per file. This makes the application truly modular, independent of file loading order, also benefits testability. See also this answer for how this pattern supposed to work.
You can use module setter and getter methods for implementation of controllers in different file.
Suppose myApp.module.js
angular.module('myApp', []); //Setter method, registring module
In myApp.homeCtrl.js
var myApp = angular.module('myApp'); // getter method, getting the module already registered.
myApp.controller('homeCtrl', [function()]{ })
For more info check this https://toddmotto.com/angular-modules-setters-getters/
The second approach your are taking about is better because it uses the already created module and doesn't create the new module but with the first approach you are using global variable that is not recommended
Scenario
I'm currently writing tests for an Angular project, and almost on every article I find, I see them creating "global" variables in a describe block, where they store dependencies to be used in the tests, like this:
describe('Some tests', function() {
var $controller, $rootScope
beforeEach(angular.mock.module('myApp'))
beforeEach(angular.mock.inject(function(_$controller_, _$rootScope_) {
$controller = _$controller_
$rootScope = _$rootScope_
}))
it('uses $controller inside', function() {
// ...
})
it('uses $rootScope inside', function() {
// ...
})
})
I have found this to be ver DRY since it creates and shares a new instance of a service/factory/etc.. for tests to use. BUT when writing a lot of tests I've noticed that I create globals and then no longer use them, and forget to delete them in the inject() leaving this traces that may cause confusion down the line.
My Confusion
So I have been injecting the dependencies on each test case and then refactor in small describe blocks to globals that don't get out of hand, like this:
describe('Some tests', function() {
beforeEach(angular.mock.module('myApp'))
it('uses $controller inside', angular.mock.inject(function($controller) {
// Test using the $controller
}))
it('uses $rootScope inside', angular.mock.inject(function($rootScope) {
// Test using $rootScope
}))
})
And this has the added benefit of thing staying local and not having to use variables that have to be searched for where they are coming from, IMHO.
The Question
Is there any problem on injecting dependencies per test instead of inside a beforeEach block?
No there is no such problem you can add dependencies according to your requirement the only problem comes at efficiency, because it has to load same file for multiple times. This problem is not a big deal when writing small amount of test cases but when you start writing more test cases it will slow down eventually. Moreover the module that you are injecting every-time might be dependent on other modules so those modules has to be loaded into memory.That's why it is preferred to use these values as global variables.
I am currently building a base for AngularJS in combination with RequireJS and so far I got everything working. there's just a little thing that I do not understand at this point. I have a file which creates the angular module, when this module is created it requires a controller and assigns it to the module. The strange thing though, the controller needs the module as dependency while in the module's file the module has not been returned yet because the require statement is executed before the return statement. This somehow seems to work but it has a bad smell to it.
Module file:
// Home is defined here and can later be used in controllers (and Services)
define('home', ['require', 'angular'], function(require, angular) {
var homeModule = angular.module('AngularBase.home', ['AngularBase.core']);
homeModule.config(['$controllerProvider', '$provide', '$compileProvider', function($controllerProvider, $provide, $compileProvider) {
// We need this in order to support lazy loading
homeModule.controller = $controllerProvider.register;
homeModule.factory = $provide.factory;
// And more, not relevant at this moment
}]);
// It loads the controller that depends on this module here
require(['modules/home/controllers/homeController'], function() {
// Dependencies loaded
});
// Yet in my mind controllers that need this module can only use it when the following return statement is called.
return homeModule;
});
Controller File:
// As you can see this controller depends on home while home hasn't returned its module yet
// Yet it seems to work just fine
define(['home'], function(home) {
home.controller('homeController', ['$scope', 'homeService', function($scope, homeService) {
$scope.title = 'Home controller';
}]);
});
I assume that it is not a good approach to do it like this and therefore I need some suggestions on how to make this happen in a clean way. I thought about grabbing the AngularBase.home module via angular.module('AngularBase.home') in the controller file and defining my controller on this. This however no longer allows me to insert a mockModule for testing in this controller via RequireJS's map function.
map: {
'*' : {
'home' : 'mock-module'
}
}
Any suggestions on how to refactor this into a more clean solution?
I have found the solution to my problem. In the end it seems to be just fine to do it the way I am currently doing it. When a file is called and has a define statement in it it will wait until all dependencies are available until the function is executed. This means that the controller will actually wait for the module to finish initializing before calling its function to register itself.
The way I am doing it above is just fine.
Source: http://www.slideshare.net/iivanoo/handlebars-and-requirejs (slides 11 till 24)
In my Angular application I adding tracing functionality, which should work as separate plugin, so if script included into HTML Angular should create service and initialize (run) it. Plugin is service because it has mandatory dependency on $rootScope.
For implementation I select to use Angular factory, like (code is in myservice.js):
angular.module('app').factory('mysevice', ['$rootScope', '$interval', serviceFunc]);
function serviceFunc($rootScope, $interval) {
return {
run: function () { ... }
}
}
And now I have problem how to immediately initialize it. My solution is to enhance Angular app run function (code is in myservice.js):
window.app.run(['mysevice', function (srvc) {
srvc.run();
}]);
Where app defined in separate main app.js file like:
var app = window.app = angular.module('app', [...]);
app.run(['$state', 'breeze', ...,
function ($state, breeze, ...) { ..real initialization.. }
The code is working fine. Both main run and run for myservice calls are fine. The application together with the service are working well, but the code looks ugly, especially storing the app in the global window object and multicasting the run function.
Is there a better way to do Angular service and initialize it immediately after app starts with some other Angular services dependencies.
You can call angular.module('app').run(function(){...}). So you will not need a global variable anymore.
Example:
angular.module('app').run(['mysevice', srvc.run.bind(srvc)]);
I've recently begun using angularjs. But it's concept of modules confuses me.
In one of the angular tutorials, there's the following code:
'use strict';
/* Services */
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
//this line's added by me
phonecatServices.constant('SomeConstant', 123);
phonecatServices.factory('Phone', ['$resource',
function($resource){
return $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
}]);
Why does angularjs require helper functions like constant or factory, when it can just as well define modules in a manner similar to that of nodejs which is much cleaner? I'm confused as to what advantages this approach has.
var $resource = require('$resource');
var SomeConstant = 123;
var Phone = $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
};
exports.SomeConstant = SomeConstant;
exports.Phone = Phone;
The answer seems centered around angular's dependency injection.
Consider angular.module to be as the api says, a global means to create/register or retrieve your module. A module needs to be created in this way so the $injector, which is a function that takes a list of module names that have been registered, can find it at the time of bootstrapping.
I wouldn't consider the factory function a 'helper', but instead actually a way of specifying to angular js's dependency injection how a service is supposed to be created. Or as the dependency injection guide puts it -- we are 'teaching' the $injector how to create a service:
// Provide the wiring information in a module
angular.module('myModule', []).
// Teach the injector how to build a 'greeter'
// Notice that greeter itself is dependent on '$window'
factory('greeter', function($window) {
// This is a factory function, and is responsible for
// creating the 'greet' service.
return {
greet: function(text) {
$window.alert(text);
}
};
});
// New injector is created from the module.
// (This is usually done automatically by angular bootstrap)
var injector = angular.injector(['myModule', 'ng']);
// Request any dependency from the injector
var greeter = injector.get('greeter');
The guide also reminds us that here, the injector is created directly from a module, but usually angular's bootstrapper takes care of that for us.
So, in short, angular.module tells angular how to resolve modules (which it does via $injector), and factory tells angular how to make or them when they're needed. In contrast, Node's modules have a one-to-one mapping with files and are resolved and made in this way.