How do I unit test a function that is defined inside a directive like the following myFunc
?
angular.module('myApp')
.directive('myDir', [function () {
var myFunc = function (arg) {
// code in here.
};
return {
restrict: 'A',
scope: { },
link: function (scope, element) {
}
};
}]);
Or how do you define testable directive specific functions that I don't want to expose outside of the directive?
How do I unit test a function that is defined inside a directive like the following myFunc
?
angular.module('myApp')
.directive('myDir', [function () {
var myFunc = function (arg) {
// code in here.
};
return {
restrict: 'A',
scope: { },
link: function (scope, element) {
}
};
}]);
Or how do you define testable directive specific functions that I don't want to expose outside of the directive?
Share Improve this question asked Jan 10, 2014 at 8:29 mkhatibmkhatib 5,2682 gold badges29 silver badges36 bronze badges2 Answers
Reset to default 6The most mon approach is to not test private methods, but instead test the public interfaces that expose their behaviour. This means that your unit test bees a contract for your public interface.
You've stated that you don't want to expose outside of the directive but of course the other option is to extract this logic into some service myDirService
and perform your logic there. In that case you'll be able to test in isolation.
As pointed out by @eddiec, ideally we shouldn't be in a situation where we need to test private methods, but we don't live in an ideal world.
The way I've found that works is by putting all private vars inside a private object - say model
and then have a getter function to access any of it's properties. The scope is accessible from any jasmine test once you pile the directive.
angular.module('myApp').directive('myDir', [function() {
return {
restrict: 'A',
scope: {
},
link: function(scope, element) {
var model = {
myPrivateVar: 'myValue'
};
model.myPrivateFunction = function(arg) {
// work with arg
};
scope.getVal = function(prop, args) {
// Getter function to access any private variables
if (model.hasOwnProperty(prop)) {
// If the requested var exists, return it.
return args ? model[prop](args) : model[prop];
}
return null;
};
}
};
}]);
I'm still not super happy with this solution, but it works for now.