D
D
Denis Denis2016-01-17 12:07:52
Angular
Denis Denis, 2016-01-17 12:07:52

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();
            });
        }
    };
});

Or at least in what direction to dig.
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-01-17
@golovewkin

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>'
}

in this case, we can only check the binding (that the controller has such a method) as part of static testing (consider code review), and the logic can simply be pulled by controllers. This has a very important advantage, since firstly we decouple the application logic from the DOM and this allows us to run our tests simply in the console without a browser, and cases with interaction with the DOM can be covered with E2E tests.
https://github.com/AngularClass/NG6-todomvc-starter/ - an example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question