Answer the question
In order to leave comments, you need to log in
How to write a test for an Angular directive?
Hello.
I'm trying to write Karma + Jasmine tests. Full understanding has not yet come.
Please tell me how to write a test for a directive
taskApp.directive('backButton', function ($location) {
return {
restrict: 'A',
link: function (scope, element) {
element.on('click', function () {
$location.path('/');
scope.$apply();
});
}
};
});
Answer the question
In order to leave comments, you need to log in
we mock the $location service, and track that our code will call the path method with the arguments we need. We create an instance of the directive (using the $compile service) and click on the element. Check if the method has been called.
But this test can be greatly simplified. We already have the ngClick directive covered by tests, so we can do this:
function HomeButtonController($location) {
var vm = this;
vm.goHome = function () {
$location.path('/');
}
}
function homeButtonDirective() {
restrict: 'E',
controller: HomeButtonController,
controllerAs: 'vm',
transclude: true,
template: '<button ng-click="vm.goHome()" ng-transclude></button>'
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question