scope keeps being undefined in angularjs unit-testing - angularjs

I am trying to unit-testing for following code, I wrote following code for unit-testing like below, I have tried so many ways to work, but I keep getting error:
'Cannot read property 'num' of undefined'
I do not know why scope is not properly set. If you have any idea about it, can you please give some advices?
var angular = require('angular');
require('angular-mocks');
describe('test directive', function () {
let $rootScope;
let $compile;
let scope;
let newScope;
let element;
beforeEach(angular.mock.inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
describe('test directive', function () {
beforeEach(function () {
newScope = $rootScope.$new();
element = $compile('<test-directive></test-directive>')(newScope);
newScope.$digest();
scope = element.isolateScope();
});
fit('scope initialized', function () {
expect(scope.num).toEqual(1);
});
});
});
module.exports = module.directive('testDirective', ['$rootScope', '$scope', function($rootScope, $scope) {
return {
template: require('./test.html'),
restrict: 'E',
controller: [
'$scope',
function ($scope) {
$scope.num = 1
$scope.sum = function(a, b) {
return a + b;
}
}]
}
}]);

The scope variable is undefined because the directive being tested does not have an isolate scope. Instead, use the scope of the element:
beforeEach(function () {
newScope = $rootScope.$new();
element = $compile('<test-directive></test-directive>')(newScope);
newScope.$digest();
̶s̶c̶o̶p̶e̶ ̶=̶ ̶e̶l̶e̶m̶e̶n̶t̶.̶i̶s̶o̶l̶a̶t̶e̶S̶c̶o̶p̶e̶(̶)̶;̶
scope = element.scope();
});
fit('scope initialized', function () {
expect(scope.num).toEqual(1);
});
Be aware that directive has a fatal flaw. It can only use it once within a given scope.

Related

How to write test-case for Directive with in Directive using jasmine

I wrote a test for my directive using jasmine testcase framework with karma testcase runner.
In my project ,I am already having one directive called
<parent-directive></parent-directive>
and i tried to include that parent directive into another one called
<child-directive></child-directive>.
Parent directive elements are converted as components called SampleComponents and included in the child directive
Sample.js
'use strict'
angular.module('Sample')
.directive('SampleHeader', SampleHeader)
function SampleHeader () {
return {
restrict: 'A',
templateUrl: 'header/header.html',
scope: {},
controller: function ($scope) {
$scope.logoutHeader = function () {
console.log('Logout call back')
require('electron').remote.app.quit()
}
}
}
}
SampleSpec.js
describe('SampleHeader', function () {
var $compile, $rootScope, elements, scope, controller
beforeEach(module('Sample'))
beforeEach(module('SampleComponenets'))
beforeEach(module('ngAnimate'))
beforeEach(module('ngRoute'))
beforeEach(module('ngMaterial'))
beforeEach(module('ngCookies'))
beforeEach(module('datatables'))
beforeEach(inject(function (_$compile_, _$rootScope_, _$q_,_$controller_) {
deferred = _$q_.defer()
$compile = _$compile_
$rootScope = _$rootScope_
controller = _$controller_
scope = $rootScope.$new()
elements = angular.element('<sample-header></sample-header>')
$compile(elements)($rootScope.$new())
$rootScope.$digest()
controller = elements.controller('SampleHeader')
scope = elements.isolateScope() || elements.scope()
scope.$digest()
}))
it('should check logoutHeader is called', function () {scope.logoutHeader()
})
})
restrict: 'A' -> it seems you created a attribute directive so you should compile the directive as a attribute (like, elements = angular.element('<div sample-header></div>')).
describe('SampleHeader', function () {
var $compile, $rootScope, elements, scope, controller
beforeEach(module('Sample'))
beforeEach(module('SampleComponenets'))
beforeEach(module('ngAnimate'))
beforeEach(module('ngRoute'))
beforeEach(module('ngMaterial'))
beforeEach(module('ngCookies'))
beforeEach(module('datatables'))
beforeEach(inject(function (_$compile_, _$rootScope_, _$q_,_$controller_) {
deferred = _$q_.defer()
$compile = _$compile_
$rootScope = _$rootScope_
controller = _$controller_
scope = $rootScope.$new()
elements = angular.element('<div sample-header></div>')
$compile(elements)($rootScope.$new())
$rootScope.$digest()
controller = elements.controller('SampleHeader')
scope = elements.isolateScope() || elements.scope()
scope.$digest()
}))
it('should check logoutHeader is called', function () {scope.logoutHeader()
})
})

how to get access to controller scope when testing directive with isolate scope

I have directive with isolate scope and controller, Is it right to write unit tests for directive and test some functional in controller scope?
And if it right, how i can get access to controller scope?
angular.module('myApp').directive('myDirecive', function () {
return {
templateUrl: 'template.html',
scope: {
data: '='
},
controller: function ($scope) {
$scope.f= function () {
$scope.value = true;
};
},
link: function ($scope) {
// some logic
});
}
};
})
describe('myDirective', function () {
'use strict';
var element,
$compile,
$rootScope,
$scope;
beforeEach(module('myApp'));
beforeEach(inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
element = compileElement();
}));
function compileElement() {
var element = angular.element('<my-directive></my-directive>');
var compiledElement = $compile(element)($scope);
$scope.$digest();
return compiledElement;
}
it('should execute f', function () {
$scope.f();
expect($scope.val).toBe(true); // there we can access to isolate scope from directive;
});
});
Controller is given the isolated scope created by the directive. Your $scope, that you pass into compile function, is used as a parent for the directive's isolate scope.
Answering how to test it, you have two options:
Access the isolated scope from the element:
var isolated = element.isolateScope();
For that, you need to have $compileProvider.debugInfoEnabled(true);
Access the isolated scope from your scope:
var isolated = $scope.childHead;
Try this
describe('myDirective', function () {
'use strict';
var element,
dirCtrlScp,
$compile,
$rootScope,
$scope;
beforeEach(module('myApp'));
beforeEach(inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
element = compileElement();
}));
function compileElement() {
var element = angular.element('<my-directive></my-directive>');
var compiledElement = $compile(element)($scope);
dirCtrlScp = element.controller;
$scope.$digest();
return compiledElement;
}
it('should execute f', function () {
dirCtrlScp.f();
expect(dirCtrlScp.value).toBe(true); // there we can access to isolate scope from directive;
});
});
Have a look at this Article

Unit Testing $routeParams in directive

I have a directive that accesses the $routeParams of the page as such:
myApp.directive("myList", function ($routeParams) {
return {
restrict: 'E',
templateUrl: 'tabs/my-list.html',
link: function (scope) {
scope.year = $routeParams.year;
}
};
});
The directive works as expected and correctly accesses the $routeParams
I am trying to test using angular-mock/jasmine. I can't figure out how to pass mock $routeParams to the directive. This is what I have:
describe('myList', function () {
var scope, compile, element, compiledDirective;
var mockParams = { 'year': 1996 };
beforeEach(function () {
module('templates', 'MyApp');
inject(function ($compile, $rootScope, $routeParams) {
compile = $compile;
scope = $rootScope.$new();
});
element = angular.element('<my-list></my-list>');
compiledDirective = compile(element)(scope);
scope.$digest();
});
it('should fill in the year', function () {
expect(scope.year).toEqual(mockParams.year);
});
});
Which obviously doesn't work because I never passed passed mockParams to the directive. Is there a way to do this?
Mock the $routeParams object mockParams using angular.extend OR do assign mockParams object directly to $routeParams. In that way $routeParams will be available before directive gets compiled.
inject(function ($compile, $rootScope, $routeParams) {
compile = $compile;
scope = $rootScope.$new();
angular.extend($routeParams, mockParams);
});

AngularJS Unit testing directive

I am doing an AngularJS unit test and use Karma - Coverage to see the result. Here is my code.
todomvc.directive('todoBlur', function () {
return function (scope, elem, attrs) {
elem.bind('blur', function () {
scope.$apply(attrs.todoBlur);
});
scope.$on('$destroy', function () {
elem.unbind('blur');
});
};
});
I have written the following test case.
describe('TodoBlur', function() {
var $compile,
$rootScope;
beforeEach(module('todomvc'));
beforeEach(inject(function(_$compile_, _$rootScope_){
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('T', function() {
var element = $compile("<todoBlur></todoBlur>")($rootScope);
$rootScope.$digest();
element.blur();
var e = $.Event('keydown');
e.which = 27;
$rootScope.trigger(e);
element.triggerHandler('keydown', 27);
element.triggerHandler('keydown', 28);
});
});
As you see, I tried many codes to try to test the keydown but none of them work. The result in Code coverage report remains unchanged. How can I test it? I am new to AngularJS and its unit test and I google and still cannot find any solutions.
Edit: I tried Unit testing Angular directive click handler and modified my code. But it still not work.
beforeEach(module('todomvc'));
describe('myCtrl', function () {
var $scope, $rootScope;
beforeEach(inject(function ($controller, _$rootScope_) {
$scope = $rootScope.$new();
$controller('myCtrl', { $scope: $scope });
$rootScope = _$rootScope_;
}));
describe('T', function () {
var element;
beforeEach(function () {
element = angular.element('<todoBlur/>');
$compile(element)(scope);
$scope.$digest();
});
});
});

Using jasmine to test angular directive that uses a controller

I am trying to write a jasmine test that will test if an angular directive I've written is working.
Here is my spec file:
describe('blurb directive', function () {
var scope, httpMock, element, controller;
beforeEach(module('mdotTamcCouncil'));
beforeEach(module('mdotTamcCouncil.core'));
beforeEach(module('blurb'));
beforeEach(inject(function (_$httpBackend_, $rootScope, $compile) {
element = angular.element('<mcgi-blurb text-key="mainPageIntro"></mcgi-blurb>');
var httpResponse = '<textarea name="content" ng-model="content"></textarea>';
scope = $rootScope.$new();
httpMock = _$httpBackend_;
httpMock.whenGET('components/blurb/blurb.html').respond(httpResponse);
element = $compile(element)(scope);
scope.$digest();
}));
it('should have some content', function () {
expect(scope.content).toBeDefined();
});
});
The value "scope.content" is always undefined and when I look at the scope object it seems to be a generic scope object that doesn't have my custom attributes on it.
Here are the other related files:
blurb-directive.js
(function () {
'use strict';
angular.module('blurb')
.directive('mcgiBlurb', blurb);
function blurb() {
return {
restrict: 'E',
replace: true,
templateUrl: jsGlobals.componentsFolder + '/blurb/blurb.html',
controller: 'BlurbController',
controllerAs: 'blurb',
bindToController: false,
scope: {
textKey: "#"
}
};
};
})();
blurb-controller.js
(function () {
angular.module('blurb')
.controller('BlurbController', ['$scope', 'blurbsFactory', 'userFactory', function ($scope, blurbsFactory, userFactory) {
$scope.content = "";
$scope.blurbs = {};
$scope.currentUser = {};
this.editMode = false;
userFactory().success(function (data) {
$scope.currentUser = data;
});
blurbsFactory().success(function (data) {
$scope.blurbs = data;
$scope.content = $scope.blurbs[$scope.textKey];
});
this.enterEditMode = function () {
this.editMode = true;
};
this.saveEdits = function () {
this.editMode = false;
$scope.blurbs[$scope.textKey] = $scope.content;
};
}]);
})();
What am I doing wrong?
The directive has isolated scope, so the scope passed to its controller and link function (if there was one), is the isolated one, different than your scope.
You may have luck getting the scope of the directive using element.isolateScope(); you may not, because of the replace: true - try to make sure. You may also access the controller instance using element.controller('mcgiBlurb').

Resources