jeudi 9 avril 2015

Undefined function in AngularJS directive unit test

I am trying to write a unit test for the toggleDetails function defined inside the following AngularJS directive:



angular.module('hadoopApp.cluster.cluster-directive', [])

.directive('cluster', [function() {
return {
templateUrl:'components/cluster/cluster.html',
restrict: 'E',
replace: true,
scope: {
clusterData: '=',
showDetails: '='
},
link: function(scope, element, attrs) {
scope.toggleDetails = function() {
console.log('Test');
scope.showDetails = !scope.showDetails;
};
},
// Default options
compile: function(tElement, tAttrs){
if (!tAttrs.showDetails) { tAttrs.showDetails = 'false'; }
}
};

}]);


And this is the unit test:



'use strict';
describe('hadoopApp.cluster module', function() {
// Given
beforeEach(module('hadoopApp.cluster.cluster-directive'));

var compile, mockBackend, rootScope;
beforeEach(inject(function($compile, $httpBackend, $rootScope) {
compile = $compile;
mockBackend = $httpBackend;
rootScope = $rootScope;
}));

var dummyCluster;
beforeEach(function() {
dummyCluster = {
id:"189",
name:"hadoop-189",
exitStatus:0
};
mockBackend.expectGET('components/cluster/cluster.html').respond(
'<div><div ng-bind="clusterData.name"></div></div>');
});

it('should toggle cluster details info', function() {
var scope = rootScope.$new();
scope.clusterData = dummyCluster;

// When
var element = compile('<cluster' +
' cluster-data="clusterData" />')(scope);
scope.$digest();
mockBackend.flush();

// Then
var compiledElementScope = element.isolateScope();
expect(compiledElementScope.showDetails).toEqual(false);

// When
console.log(compiledElementScope);
compiledElementScope.toggleDetails();

// Then
expect(compiledElementScope.showDetails).toEqual(true);
});

afterEach(function() {
mockBackend.verifyNoOutstandingExpectation();
mockBackend.verifyNoOutstandingRequest();
});
});


The test fails when calling compiledElementScope.toggleDetails() because the toggleDetails function is undefined:



TypeError: undefined is not a function


Printing the content of the isolated scope inside compiledElementScope I can see that in fact the function is not included in the object.


So, it looks like the toggleDetails function is not included in the isolated scope but I don't know why.


Aucun commentaire:

Enregistrer un commentaire