How to mock ng-grid when unit testing a controller - angularjs

I'm currently trying to write tests for existing blocks of code and running into an issue with a controller that has a nested ng-grid inside of it. The issue comes from the controller trying to interact with the grid on initialization.
Testing Software
node#0.10.14
karma#0.10.2
karma-jasmine#0.1.5
karma-chrome-launcher#0.1.2
My Test:
define(["angularjs", "angular-mocks", "jquery",
"js/3.0/report.app",
"js/3.0/report.controller",
"js/3.0/report.columns"
],
function(angular, ngMocks, jquery, oARModule, oARCtrl, ARColumns) {
"use strict";
describe("Report Center Unit Tests", function() {
var oModule;
beforeEach(function() {
oModule = angular.module("advertiser_report");
module("advertiser_report");
});
it("Advertiser Report Module should be registered", function() {
expect(oModule).not.toBeNull();
});
describe("Advertiser Report Controller", function() {
var oCtrl, scope;
beforeEach(inject(function($rootScope, $controller, $compile) {
var el = document.createElement('div');
el.setAttribute('ng-grid','gridOptions');
el.className = 'gridStyle';
scope = $rootScope.$new();
$compile(el)(scope);
oCtrl = $controller('ARController', {
$scope: scope
});
}));
it("Advertiser Report controller should be registered", function() {
expect(oCtrl).not.toBeNull();
});
});
});
});
You'll see where I've tried to create and compile an element with the ng-grid attribute. Without doing this I get the following error:
TypeError: Cannot read property 'columns' of undefined
Which is a result of the controller attempting to call things like
$scope.gridOptions.$gridScope.columns.each
So I added the creation of a div with ng-grid attribute, and got a new error:
TypeError: Cannot set property 'gridDim' of undefined
So, I tried to add scope.gridOptions before the $controller call, but this brought me back to the original error. I've been searching for way to make this work without rewriting the controller and/or templates, since they are currently working correctly in production.

Your (major!) problem here is that the controller is making assumptions about a View. It should not know about and thus not interact with ng-grid. Controllers should be View-independent! That quality (and Dependency Injection) is what makes controllers highly testable. The controller should only change the ViewModel (i.e. its $scope), and in testing you validate that the ViewModel is correct.
Doing otherwise goes against the MVVM paradigm and best practices.
If you feel like you must access the View (i.e. directives, DOM elements, etc...) from the controller, you are likely doing something wrong.

The problem in the second Failing test is gridOptions and myData is not defined prior to the compilation. Notice the sequence of the 2 statements.
Passing
oCtrl = $controller('MainCtrl', { $scope: $scope });
$compile(elm)($scope);
Failing
$compile(elm)($scope);
oCtrl = $controller('MainCtrl', { $scope: $scope });
In both cases you are trying to use the same html
elm = angular.element('<div ng-grid="gridOptions" style="width: 1000px; height: 1000px"></div>');
I suggest you get rid of
oCtrl = $controller('MainCtrl', { $scope: $scope });
maneuvers and use the following HTML element instead
elm = angular.element('<div ng-controller="MainCtrl"
ng-grid="gridOptions" style="width: 1000px; height: 1000px"></div>');
Notice ng-controller="MainCtrl".
So the end story is that you need gridOptions defined somewhere so
that it ngGrid can access it. And make sure gridOptions dependent
code in controller is deferred in a $timeout.
Also take a look at the slight changes in app.js
$timeout(function(){
//your gridOptions dependent code
$scope.gridOptions.$gridScope.columns.each(function(){
return;
});
});
Here is the working plnkr.

Related

Angular Dependencies Between Modules

I'm facing a problem using Dependency Injection between modules.
I have a module that implements a directive I need to use in other applications.
I added the dependency from this module in another app declaration like this:
angular.module('mainApp', ['ngRoute', 'directiveApp']);
However, the methods implemented into directiveApp.controller, doesn't seem to be visible from a page of MainApp, since the directive can't run a method it needs from their controller.
I know it's a little confusing, so I put an example in this plunker, that shows the problem I'm facing.
When you inject another module into your own, the controllers and directives it implements become available, but you need to use them properly.
The way you are trying to do is not possible, you can do something like this:
http://plnkr.co/edit/peHH226vxtkI48RFZ3Eq?p=preview
<body ng-controller="MainCtrl">
<h1>Value: {{name}}!</h1>
<button ng-click="mainModule()">Call a function in the main module!</button>
<div ng-controller="SubCtrl">
{{name}}
<button ng-click="dependentModule()">Call a function in the dependent module!</button>
</div>
</body>
But notice that you have two different $scopes and consequently two different name variables.
That means your dependentModule() function belongs to your SubCtrl and you can only use it inside its own $scope
That's not recommended, but if you really need to, you can use the other controllers on your own methods and then copy the results:
http://plnkr.co/edit/ranK9n08NNVuSKIGX15G?p=preview
main.controller("MainCtrl", function($scope, $controller) {
$scope.name = "Initial value";
$scope.mainModule = function() {
$scope.name = "a function in the same module";
};
$scope.bridgeFunction = function(){
// Create a new scope
var injectedScope = $scope.$new();
// Use it on the other controller
$controller('SubCtrl',{$scope : injectedScope });
// Call the methdo on the controller
testCtrl1ViewModel.dependentModule(); //And call the method on the newScope.
// Copy the result from that scope into your own
$scope.name = testCtrl1ViewModel.name;
}
});
A third option is to merge the two scopes, although this can get very messy, it is possible:
http://plnkr.co/edit/1NKStMuYy0e00dhuWKUD?p=preview
main.controller("MainCtrl", function($scope, $controller) {
$scope.name = "Initial value";
//This can get very messy, but it is possible to merge the two scopes:
$controller('SubCtrl',{$scope : $scope });
$scope.mainModule = function() {
$scope.name = "a function in the same module";
};
});
Hope that helps

Unit testing controllers in angularJS

I am having a hard time understanding unit tests in angularJs. I have just started with unit tests and the syntax seems weird to me. Below is the code for testing a controller :
describe('PhoneCat controllers', function() {
describe('PhoneListCtrl', function(){
beforeEach(module('phonecatApp'));
it('should create "phones" model with 3 phones',
inject(function($controller) {
var scope = {},
ctrl = $controller('PhoneListCtrl', {$scope:scope});
expect(scope.phones.length).toBe(3);
}));
});
});
What I can understand from this syntax is that before each it block phonecatApp is initialised and that $controller service is used to get an instance of PhoneListCtrl controller.
However I am not able to understand the scope thing here. Can someone elaborate on whats behind getting the scope of the controller on this line.
ctrl = $controller('PhoneListCtrl', {$scope:scope});
Normally, at runtime, angular creates a scope and injects it into the controller function to instantiate it.
In your unit test, you instead want to create the scope by yourself and pass it to the controller function, in order to be able to see if it indeed has 3 phones after construction (for example).
You might also want to inject mock services instead of the real ones into your controller. That's what the array of objects allows in
$controller('PhoneListCtrl', {$scope:scope});
It tells angular: create an instance of the controller named 'PhoneListCtrl', but instead of creating and injecting a scope, use the one I give you.
If your controller depended on a service 'phoneService', and you wanted to inject a mock phoneService, you could do
var mockPhoneService = ...;
$controller('PhoneListCtrl', {
$scope: scope,
phoneService: mockPhoneService
});
It's not necessary to inject the scope, you can directly use the instance of controller to call the controller's functions and objects.In your example you can use like below, this will give the same result set as yours
describe('PhoneCat controllers', function() {
describe('PhoneListCtrl', function(){
beforeEach(module('phonecatApp'));
it('should create "phones" model with 3 phones',
inject(function($controller) {
var ctrl = $controller('PhoneListCtrl');
expect(ctrl.phones.length).toBe(3);
}));
});
});
and for you information each time the controller is instantiated it is bound to a $scope variable which is derived from $rootScope (i.e: child of rootscope). So you need to pass the $scope to grab the instance of controller and I am doing same thing in above example.

Cannot get the scope os a controller in anugular.js

I am trying to test a javascript file which has in it a controller and some HTML DOM elements which it interacts with.
The class under test is:
function BaseConceptMenu(options) {
var baseConceptMenu = new BaseMenu(options);
//Public function -->Method under Test
function showCodeConceptToolbar() {
var scope = angular.element('#toolbar').scope();
scope.$apply(function() {
scope.toolbarController.show(baseConceptMenu.someObject);
});
}
I am trying to mock the controller and create the HTML DOM element "toolbar" on the fly without trying to create an external HTML template just for the sake of testing.
I am trying to create the div "toolbar" inside the before each and mocking the "CodeConceptToolbarController" controller
beforeEach(inject(function ($rootScope, $compile) {
elm = document.createElement('div');
elm.id = 'toolbar';
scope = $rootScope.$new();
createController = function() {
return $controller('CodeConceptToolbarController', {
$scope: scope
});
};
$compile(elm)(scope);
scope.$digest();
}));
However when I try to test it as below
it('Test Code ConeptToolbarContoller', function() {
// var toolbar = angular.element('#toolbar');
document.getElementById("toolbar").scope().toolbarController = createController();
//As of now,not doing any-idepth testing
//Just a base test call
var menu = new BaseConceptMenu({});
expect(menu.show()).toBe(true);
});
I get this error
TypeError: Cannot read property 'scope' of null
Could anyone provide a way to test this?
or is there a better way to test this?
currently I am using Maven-jasmine plugin
Two problems:
As per https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById, "Elements not in the document are not searched by getElementById." $compile doesn't insert the element into the DOM - it just sets up appropriate bindings (and does smart things like handling nested directives inside your template string). Your getElementById will fail to find a match. You need to insert the element into the DOM somewhere.
getElementById returns a raw HTML DOM element. To get the Angular scope from it, the docs call for wrapping it in angular.element():
var element = document.getElementById(id);
angular.element(element).scope()...
This pattern will provide the Angular wrapper around the element to do the rest of the magic. It's all based on jqLite, which isn't jQuery but does follow a lot of the same patterns. For those used to jQuery, think of it like writing $(element).

Angular Testing DOM after update by Factory

Ok, I'm trying to test the outcome of a function that updates the DOM>
I have a directive that loads a template via url.
Then a controller calls a factory method to update the html table with data.
I have the tests showing that I can get the data that is all good.
but how can I test that the updates to the table have taken place?
I am using NodeJS with Karma and Jasmine.
I have followed tutorials on how to load in templates, and I have that working, I can load and access the templates in my test fine.
but when I run the method to update the table, the tests fail.
I'll give an scaled down example of what I'm trying to do. Note, this is just demo code, Not a working app.
Template.
<table><tr><td class="cell1"></td></tr></table>
Directive.
dataTable.directive('dataTable', function () {
return {
restrict: 'E',
templateUrl: 'path/to/template/dataTable.html'
};
});
Controller
dataTable.controller('dataTableController', ['$scope', 'dataTableFactory',
function ($scope, dataTableFactory){
$scope.updateTable = function(){
dataTableFactory.loadData();
// code to load data from dataTableFactory here! //
dataTableFactory.updateTable();
}
}])
Factory
dataTable.factory('dataTableFactory',['$document',function($document){
var _tableData;
return(
"tableData": _tableData,
loadData: function(){
// code to get data and populate _tableData.
}
updateTable: function(){
$document.find('.cell1').append(this.tableData.data);
}
)
}])
Unit Test
describe('dataTable Tests', function () {
var scope, element, $compile, mDataTableFactory, controller, tableData, doc, factory;
beforeEach(module('dataTable'));
beforeEach(module('app.templates')); // setup via ng-html2js
beforeEach(inject(function (_$rootScope_, _$compile_,_$controller_,_dataTableFactory_) {
scope = _$rootScope_.$new();
doc = _$compile_('<flood-guidance></flood-guidance>')(scope);
factory = _dataTableFactory_;
controller = _$controller_('dataTableController', {
$scope: scope,
$element: doc,
dataTableFactory: factory
});
scope.$digest();
}));
it("Template should contain the cell cell1", function(){
expect(doc.find('.cell1').contents().length).toBe(0);
expect(doc.find('.cell1').html()).toBeDefined();
});
// Passes fine, so I know the template loads ok.
it('Should show data in cell1',function(){
factory.tableData = {data: 'someData'};
scope.updateTable();
expect(doc.find('.cell1').contents().length).toBe(1);
expect(doc.find('.cell1').html()).toBe('SomeData');
});
});
});
Test Ouptut
Expected 0 to be 1. Expected '' to be 'someData'.
If I put the updateTable code in to the controller and call the update function there, the test passes, but I'd like to have this in a factory, how can I make this test pass (the app runs and works as expected, I just can't get a working test).
I understand this kind of testing is more focused on the UI and not exactly 'Unit Testing' but is it possible to do this?
So essentially updateTable cannot find the changes performed by factory.tableData. I guess the problem may be due to the way how your factory exposes the _tableData property.
Could you try to modify your factory like this:
dataTable.factory('dataTableFactory',['$document',function($document){
var _tableData;
return(
getTableData: function() { return _tableData; },
setTableData: function(newVal) { _tableData = newVal; },
loadData: function(){
// code to get data and populate _tableData.
}
updateTable: function(){
$document.find('.cell1').append(this.tableData.data);
}
)
}])
and then of course use the setter/getter accordingly. See if it works this way.
OK so I'm still not sure if I fully get your intention but here is a fiddle with my refactored example.
http://jsfiddle.net/ene4jebb/1/
First of all the factory shouldn't touch the DOM, that's the directives responsibility. Thus my rework passes the cellvalue (new scope property) to the directive, which renders it. Now when you call setTableData (which will change _tableData.data) and since in test environment call the $digest loop yourself, the directive will automatically redraw the new stuff.
Controller is kept thin as possible thus only providing a scope property to the factory.
As said not sure if you were after this, but hope it helps. If there are any questions just ask.

angularjs how to define a new property on $scope without a view

I am trying BDD with Jasmine and angularJS app. My requirement is to create a select element in my view which gets it's data from a factory. So in true spirit of BDD, I am writing my factory and controller first before I start writing my view.
My test for factory:
describe('getTypeOfUnit', function(){
it('should return typeofunits', inject(function(getTypeOfUnit){
expect(getTypeOfUnit).not.toBeNull();
expect(getTypeOfUnit instanceof Array).toBeTruthy();
expect(getTypeOfUnit.length).toBeGreaterThan(0);
})) ;
});
So I am testing that my data is not null, is an array and contains at least one item. It fails since there is no factory.
This is the factory to make the tests pass:
angular.module('myApp.services', [])
.factory('getTypeOfUnit', function(){
var factory = ['Research Lab', 'Acedamic Unit', 'Misc'];
return factory;
});
Now onto the controller. Here is the empty controller:
angular.module('myApp.controllers', [])
.controller('describeUnitController',[function($scope){
console.log('exiting describeUnit');
}]);
And tests for controller:
describe('controllers', function(){
var describeScope;
beforeEach(function(){
module('myApp.controllers');
inject(function($rootScope, $controller){
console.log('injecting contoller and rootscope in beforeEach');
describeScope = $rootScope.$new();
var describerController = $controller('describeUnitController', {$scope: describeScope});
});
}) ;
it('should create non empty "typeOfUnitsModel"', function() {
expect(describeScope["typeOfUnits"]).toBeDefined();
var typeOfUnits = describeScope.typeOfUnits;
expect(typeOfUnits instanceof Array).toBeTruthy();
expect(typeOfUnits.length).toBeGreaterThan(0);
});
});
So I am testing that my controller returns a non empty array. Same as the service. These tests fail. So next step is to define a property on the scope object in the controller:
.controller('describeUnitController',[function($scope){
$scope.typeOfUnits = [];
console.log('exiting describeUnit');
}]);
Now I get an error:
TypeError: Cannot set property 'typeOfUnits' of undefined
Why does the controller not know about the scope? I thought DI would automatically make it available?
Thank you in advance. Also please comment on my tests.
Found two mistakes with my code:
The controller does not know about the $scope. Not sure why. So I can do one of the following:
.controller('describeUnitController',['$scope',function($scope){
$scope.typeOfUnits = [];
console.log('exiting describeUnit');
}]);
OR
.controller('describeUnitController',function describeUnitController($scope){
$scope.typeOfUnits = [];
console.log('exiting describeUnit');
});
I am not sure why it is this way. But lesson learned.
I then tried to use the service as follows:
.controller('describeUnitController',function describeUnitController($scope, GetTypeOfUnit){
$scope.typeOfUnits = getTypeOfUnit;
});
This gave me the famous Error: unknown provider for GetTypeOfUnit
Apparantly, I have to add the services module to the factory module in order to use the service and make the tests pass. But my app.js has them all defined:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers','ui.bootstrap','$strap.directives'])
But since I am testing, I have to load the services module in the controllers module as well. If the app was loading (like in the browser), I would not have to do this.
Am I understanding this correctly? Thank you all.

Resources