Isolation with Angular on karma jasmine - javascript

I have a set of tests that are spread across 2 modules.
The first module has tests and for it's dependencies i declare mocks to test it without any influence from it's dependent module, like so:
beforeEach(function(){
angular.mock.module(function ($provide) {
$provide.value("mockServiceFromModule1", mockServiceFromModule1);
$provide.value("mockServiceFromModule2", mockServiceFromModule2);
});
angular.module('module1', []);
angular.module('module2', []);
angular.mock.module('moduleThatIAmTesting');
angular.mock.inject(function (_$rootScope_, _$q_, _$httpBackend_, ..., somethingFromTestModule) {
});
})
The second module has a series of tests and all of them pass when i run only them.
beforeEach(function(){
angular.mock.module('module1');
angular.mock.inject(function (_$rootScope_, _$q_, _$httpBackend_, ..., somethingFromModule1) {
});
})
Both tests when run with f(Running only them) works, but when i run the whole test suit i get errors, specially regarding module declaration or $httpBackend.
How can i make jasmine run each test as if they were the only tests?
It seems i am messing with the angular/modules/$httpBackEnd on each test and the changes are being propagated when it starts a new test.
Update 1
I have a jsFiddle representing the issue .
The structure of the problem is :
Some test is ran with a mock dependant module
Later another test wants to test the actual mocked module
Since the first moldule was already loaded we can't overwritte it and the test fails.
On the JSFiddle the error about $httpBackend without nothing to flush is because the request for the expectedGet is never hit, and it's never hit because of the previously loaded empty module
It's important to notice that the ORDER of the tests is the only thing relevant to failing as in this JSFiddle with the same tests they pass.
I could of course make a tests order and bypass this but i am aiming to find a way to do the tests with isolation without worrying about other tests side effects.

The problem you are experiencing is due to the nature of how the $compileProvider handles a new directive being registered with a pre-existing name.
In short; You are not overriding your old directive, you are creating a secondary one with the same name. As such, the original implementation runs and tries to grab baz.html and $httpBackend throws as you have not set up an expectation for that call.
See this updated fiddle that did two changes from your original fiddle.
Do not inject the parentModule to your childModule spec. That line is not needed and it is part of the reason you are seeing these errors. Oh and angular.module is evil in the land of tests. Try to not use it.
Decorate the original directive if you wish to roll with the same name as the original one, or name it something else. I've opted for naming it something else in the fiddle, but I have supplied code at the end of my answer to show the decorator way.
Here's a screenshot of what happens in the following scenario:
Module A registers a directive called baz.
Module B depends on module A.
Module B registers a directive called baz.
As you can probably imagine, in order for the module system to not insta-gib itself by letting people overwrite eachothers directives - the $compileProvider will simply register another directive with the same name. And both will run.
Take this ng-click example or this article outlining how we can leverage multiple directives with the same name.
See the attached screenshot below for what your situation looks like.
The code on lines 71 to 73 is where you could implement solution #2 that I mentioned in the start of my answer.
Decorating baz
In your beforeEach for testModule, replace the following:
$compileProvider.directive('baz', function () {
return {
restrict: 'E',
template: '{{value}}<div ng-transclude></div>',
controllerAs: 'bazController',
controller: function ($scope, fooService) {
$scope.value = 'baz' + fooService.get()
},
transclude: true
};
});
With this:
$provide.decorator('bazDirective', function ($delegate) {
var dir = $delegate[0];
dir.template = '{{value}}<div ng-transclude></div>';
dir.controller = function ($scope, fooService) {
$scope.value = 'baz' + fooService.get();
};
delete dir.templateUrl;
return $delegate;
});
jsFiddle showing the decorator approach
What about the call to angular.module('parent', [])?
You should not call angular.module('name', []) in your specs, unless you happen to be using the angular-module gist. And even then it's not doing much for you in the land of testing.
Only ever use .mock.module or window.module, as otherwise you will kill your upcoming specs that relate to the specified module, as you have effectively killed the module definition for the rest of the spec run.
Furthermore, the directive definition of baz from parentModule will automatically be available in your testModule spec due to the following:
angular.module('parent', []).directive('baz', fn());
angular.module('child', ['parent']);
// In your test:
module('child'); // Will automatically fetch the modules that 'child' depend on.
So, even if we kill the angular.module('parent', []) call in your spec, the original baz definition will still be loaded.
As such, the HTTP request flies off due to the nature of $compileProvider supporting multiple directives with the same name, and that's the reason your spec suite is failing.
Also, as a last note; You are configuring undefined modules in your beforeEach blocks. If the goal is to configure the module of your test, you are in the wrong.
The syntax is as follows:
mock.module('child', function ($compileProvider, /** etc **/) {
});
// Not this:
mock.module('child');
mock.module(function ($compileProvider, /** etc **/) {
});
This can be seen in the screenshot I posted. The $$moduleName property of your mocked baz definition is undefined, whereas I am assuming you would want that to be child.

Related

Delete or Redefine angular module

with the following I would like to be able to define a module the first time and then change it on the fly later on. The reason is that my modules are dynamically generated and I'd rather reload one module than the whole app once One JavaScript file changes; it is Huge and Slow to load. The JS files are watched for changes and loaded lazily but always the initial module persists, i.e. 'This will be logged the first time' always gets logged even though the new JavaScript executes it does not overwrite the old module.
I think this would be a great tool for the AngularJS community but I don't know as yet it if it's already possible (I keep reading it's not). Alternatively I'd be happy if I could achieve the same using controllers/directives/1.5components
Thank you
// First state of angular module
angular.module('myApp.view1', [])
.controller('View1Ctrl', ['$scope',function($scope) {
$scope.buttonClick = function () {
console.log('This will be logged first time');
}
}]);
// Second state of angular module
angular.module('myApp.view1', [])
.controller('View1Ctrl', ['$scope',function($scope) {
$scope.buttonClick = function () {
console.log('This will be logged the second time');
}
}]);
<button ng-click="buttonClick()">Button</button>
However that's not a groovy thing to redefine your angular module.
You can do that by just defining the angular.module('YourAppModule', ['Dependencies']);
This will overwrite your previously bootstrapped module.
I have made a feature request for this issue, but unfortunately it's been denied, understandably so. Further details are here: https://github.com/angular/angular.js/issues/14743#issuecomment-224868610

How to bootstrap angular at the start of each karma/jasmine test file?

Is it possible to have angular bootstrap the app at the beginning of each test file? Instead of the current behavior, which has the app bootstrap at the beginning of the series of tests, and then the same instance is used throughout all the test files (we have about 600 tests throughout ~60 files right now)?
We have beforeEach statements to handle clean-up and that doesn't help. In fact, seems sometimes the beforeEach statements are altogether skipped for no apparent reason (possible memory leak with test runner).
So the route I would like to take this is to have each test file bootstrap the angular app, so that the state is completely reset, instead of reusing dependency injection (ie. services) that had state set by a different test.
You don't need to bootstrap the app for the tests. That's why we have angular-mock. With angular.module('app.module') we load the module we need for our test and that module contains the component we want to test. Since angular-mock is not the cause for the memory leaks, there can be several reasons for them. One of the most common reasons for memory leaks is jasmine itself and the way we usually write the tests. The variables we use for the dependencies we inject in our test and are defined on the describe scope and cannot be collected by the GC when the tests finish. This is because there are references of those variables in the it blocks that cannot be garbage collected because the variables still live in some other scope of the tests tree. Another problem can be the compiled elements that should also be cleaned up after each test. So you probably need to clean-up the following things:
compiled element when using $compile for testing directives
all
variables in the describe functions scope
You can do something like this:
describe('testSuite', function () {
var suite = {};
beforeEach(module('app'));
beforeEach(inject(function ($rootScope, $compile, heavyLoad) {
suite.$rootScope = $rootScope;
suite.$compile = $compile;
suite.heavyLoad = heavyLoad;
suite.$scope = $rootScope.$new();
spyOn(suite.heavyLoad, 'getHeavyString').and.callThrough();
spyOn(suite.heavyLoad, 'getHeavyObject').and.callThrough();
spyOn(suite.heavyLoad, 'getHeavyList').and.callThrough();
}));
// NOTE: cleanup
afterEach(function () {
// NOTE: prevents DOM elements leak
suite.element.remove();
});
afterAll(function () {
// NOTE: prevents memory leaks because of JavaScript closures created for
// jasmine syntax (beforeEach, afterEach, beforeAll, afterAll, it..).
suite = null;
});
suite.compileDirective = function (template) {
suite.element = suite.$compile(template)(suite.$scope);
suite.directiveScope = suite.element.isolateScope();
suite.directiveController = suite.element.controller('heavyLoad');
};
it('should compile correctly', function () {
// given
var givenTemplate = '<div heavy-load></div>';
// when
suite.compileDirective(givenTemplate);
// then
expect(suite.directiveScope.title).toBeDefined();
expect(suite.directiveScope.items).toBeDefined();
expect(suite.heavyLoad.getHeavyString).toHaveBeenCalled();
expect(suite.heavyLoad.getHeavyList).toHaveBeenCalled();
});
});
Taken from here.
This should reduce your memory leaks significantly.
You should also take a look at your module structure and the dependency graph your modules have, cause you might have some modules that are not needed for some tests but they are loaded anyway. They can be heavy on memory or contain memory leaks in them and can make you additional problems.
You can also take a look at this github project.

AngularJS : directive function not called

The function that I'm providing to define my directive is never called. It used to work fine but suddenly stopped working and I have no idea why.
Here's my directive:
portalApp.directive('contactPanel', function () {
console.log("NEVER SHOWN!");
return {
restrict: 'AE',
replace: 'true',
templateUrl: 'partials/account/contactPanel.html',
scope: {
contact: '=contact',
primaryRoleName: '#',
roleName: '#',
primary: '=primary',
locations: '=locations'
},
controller: function (userService, $rootScope, $scope) {
...snip...
}
};
});
and here an example of its use:
<contact-panel contact="user.account.contacts.billing" role-name="billing"
locations="locations"></contact-panel>
Note that I'm using the correct casing, i.e. camel-case in JS and hyphenation in HTML.
The key clue is that the message that's logged in the second line (i.e. 'NEVER SHOWN!') never shows up in the console. If I log a message immediately before the directive declaration then that shows up, so this code is being executed by the interpreter, but the framework is just never using my declaration.
I'd love to have an answer obviously, but I'd also love to hear of some approaches to debug this kind of problem.
I can see only 2 possibilities that would exhibit the behavior you described. Either the HTML with the directive was not compiled or the directive is not registered.
The "not compiled" case could be because the directive is used outside of the Angular app, for example:
<div ng-app="portalApp">
...
</div>
...
<contact-panel></contact-panel>
Or, if you added the HTML dynamically, but did not $compile and link it.
The "not registered" case could be due to re-registration of the app's module. In other words, you might have the following case:
var portalApp = angular.module("portalApp", []);
portalApp.directive("contactPanel", function(){...});
// then elsewhere you use a setter:
angular.module("portalApp", []).controller("FooCtrl", function(){});
// instead of the getter:
// var app = angular.module("portalApp");
The second call to angular.module("portalApp", []) removes the previous registration of .directive("contactPanel", ....
I figured out the cause of this problem. At some point I must've accidentally moved the directive into a configuration block like this:
portalApp.config(function ($stateProvider, $urlRouterProvider) {
portalApp.directive('contactPanel', function () {
console.log("NEVER SHOWN!");
return {
...snip...
};
});
});
Once I moved it back out of the configuration block and into the global scope the directive immediately rendered as it should.
The reason why this doesn't work is that angular runs the configuration code after it's run the directives, like this:
runInvokeQueue(moduleFn._invokeQueue); // runs directives
runInvokeQueue(moduleFn._configBlocks); // runs config blocks
So things added to the _invokeQueue (which the directive() function does) from within a config block will never be executed.
Thank you to all those who tried to help.

How to properly test an AngularJS Controller Function

We just started implementing jasmine tests in our AngularJS project and I have a question:
We want to test this controller function:
$scope.deleteClick = function () {
$scope.processing = true;
peopleNotesSrv.deleteNote($scope.currentOperator.operatorId, $scope.noteId, $scope.deleteSuccessCallback, $scope.deleteErrorCallback);
};
We wrote this following test:
it('deleteClick should pass proper parameters to peopleNoteSrv', function () {
$controllerConstructor('PeopleNoteEditCtrl', { $scope: $scope });
$scope.noteId = 5;
expect(function () { $scope.deleteClick(); }).not.toThrow();
});
This test makes sure that when we call the $scope.deleteClick() function that $scope.processing is set to true and that the call to peopleNotesSrv doesn't throw any errors because of invalid arguments. We are testing the two callback functions in separate tests.
Should we be testing that the peopleNotesSrv.deleteNote function was called so the test is more explicit? The way this test is written right now it doesn't really tell someone what the deleteClick() function does under the hood and that seems to be incorrect.
Ask yourself what you'd do if you had developed it using TDD. It pretty much goes the direction Sam pointed out, but here are some examples:
Controller Tests
start writing a test which would expect a deleteClick to exist.
Expect deleteClick to setup the loading state (check for processing = true)
Test whether a service is injected into the controller (peopleNotesSrv)
Check whether deleteClick calls the service (as already mentioned via spies)
Verify that $scope.noteId and the other $scope.params are present and set
This is as far as it relates to the Controller. All the criteria whether it fails or throws errors etc. should be tested in a Service.spec. Since I don't know your service in detail here some examples
Service Tests
Ensure deleteNote exists
Check what happens if wrong number of arguments (less or more) are supplied
Make some positive tests (like your noteId = 5)
Make some negative tests
Ensure callbacks are properly called
... and so on.
Testing for validity in controllers doesn't make a lot of sense because than you'd need to do it for every Controller you have out there. By isolating the Service as a separate Unit of Test and ensure that it fulfills all the requirements you can just use it without testing. It's kinda the same as you never would test jQuery features or in case of Angular jQLite, since you simply expect them to do what they should :)
EDIT:
Make controller tests fail on service call
Pretty easy lets take this example. First we create our Service Test to ensure that the call fails if not the proper number of arguments is supplied:
describe('Service: peopleNoteSrv', function () {
// load the service's module
beforeEach(module('angularControllerServicecallApp'));
// instantiate service
var peopleNoteSrv;
beforeEach(inject(function (_peopleNoteSrv_) {
peopleNoteSrv = _peopleNoteSrv_;
}));
it('should throw error on false number of arguments', function () {
expect(function() { peopleNoteSrv.deleteNote('justOneParameter'); }).toThrow();
});
});
Now to ensure that the test passes lets create the error throwing part in our service method
angular.module('angularControllerServicecallApp')
.service('peopleNoteSrv', function peopleNoteSrv() {
this.deleteNote = function(param1, param2, param3) {
if(arguments.length !== 3)
throw Error('Invalid number of arguments supplied');
return "OK";
};
});
Now lets create 2 demo controllers, FirstCtrl will do it properly, but SecondCtrl should fail
angular.module('angularControllerServicecallApp')
.controller('FirstCtrl', function ($scope, peopleNoteSrv) {
$scope.doIt = function() {
return peopleNoteSrv.deleteNote('param1', 'param2', 'param3');
}
});
angular.module('angularControllerServicecallApp')
.controller('SecondCtrl', function ($scope, peopleNoteSrv) {
$scope.doIt = function() {
return peopleNoteSrv.deleteNote('onlyOneParameter');
}
});
And both controller as a demo have following test:
it('should call Service properly', function () {
expect(scope.doIt()).toBe("OK");
});
Karma now spits out something like this:
Error: Invalid number of arguments supplied
at [PATH]/app/scripts/services/peoplenotesrv.js:15
at [PATH]/app/scripts/controllers/second.js:13
at [PATH]/test/spec/controllers/second.js:20
Thus you exactly know that you missed to update SecondCtrl. Of course this should work for any of your tests consuming the Service method.
Hope that's what you meant.
I think the answer is that it depends.
There are two cases:
1 - You also have a suite of tests for the peopleNotesSrv service.
In this case I would leave this test as-is or check a few more things around the specific functionality of $scope.deleteClick(), such as if there are any watchers on $scope.processing that do anything specific regarding a .deleteClick() call.
2 - You do not have any tests for all the possible functionality for the peopleNotesSrv service.
In this case I would write a more explicit test that does check that the .deleteNote() actually performed it's job.
In my opinion you should really build tests up and try to not test the same thing in more than one place, as this adds extra work and could produce holes in the tests if you think, "Well I can just test this specific case when it gets called from a specific function that calls it."
What if you ever want to reuse that deletNote() as part of a bigger function in a different place?Then you need to write another test for the same code because it is being called from a different function.
So I would aim for case 1, this way you can write all your tests for that service and then trust that those tests cover the rest of this particular test. If you throw errors on bad input or for failures to actually delete a note, you should trust that other code to test what it was designed to test. This will greatly speed up your test-writing time and increase the chance that your tests cover all the cases. It also keeps all the tests for that service in the same place in your test code.
I think also a good question to start with is what kind of test is this? Unit Test or End-to-End test?
I was assuming it was a Unit Test for my answer, if it was an End-to-End test, then you might want to keep following the function calls to verify everything is happening as you expect.
Here are some links on Unit Tests, End-to-End tests, and a pretty good article about both and Angular.
What's the difference between unit, functional, acceptance, and integration tests? (End-to-End tests can also be called Integration test)
http://www.sitepoint.com/unit-and-e2e-testing-in-angularjs/

Angularjs module dependencies loop

I am curious and still can not explain dependency loop (passed) in this case.
angular.module('mainApp', ['addon.dashboard']).factory('Test', function(){
return {
hello: 'moto'
};
});
angular.module('addon.dashboard', ['mainApp']).controller('Demo', function(Test){
console.log(Test.hello);
});
That is a sample code in my app. The mainApp module require to inject addon.dashboard module. Otherwise, addon.dashboard module require to inject mainApp module.
We can see that it may loop here. But it work in my app. The controller Demo actually output moto into console.
How does angular deal with loop injection like that?
You might want to look into the angular code (especially the loadModules method). Basically there is a HashMap that contains all the modules loaded. If its not in the HashMap, it puts it into that and then goes ahead with initializing the rest of the module. IF its already in the set, it will return immediately.
So, in your case, lets say mainApp gets loaded first. It puts it into loadedModules and the goes to find its dependencies. When it finds addon.dashboard, it finds that mainApp is a dependency, but its already present in loadedModules, so it returns immediately.
Its a lot better if you breakpoint into the "loadModules" method of angular.js

Categories

Resources