Apr 21, 2016

Unit test for Directive with template - AngularJs

As we are adding unit test for directive, its implementation can vary from simple to very complex.
The complex implementation require more knowledge about how to write deeper test in order to get better tested coverage.

To start testing you'll need to start with $compile of DOM element, link function, to angular's controller or anonymous function controller, to template...  

Here are the sources to learn about writing directive's unit test.

  • very interactive and straight forward Directive Unit Testing Guide
  • covered topics
    • "setup karma.config.js"
    • "how to start testing directive", 
    • "working with template" (ng-html2js processor)
  • has more thorough coverage of possible solutions required for Directive unit testing

2) Testing AngularJS directive controllers with Jasmine and Karma (1st tutorial) (2nd tutorial
  • Covered
    • setup sample karma.config.js
    • unit test of anonymous function as controller
    • make use of ng-html2js process
  • The best part of this tutorial is in "2nd tutorial" link, it provided sample of Directive using anonymous function as its controller
    • Testing with anonymous function as controller
      
      angular.directive('myDirective', function() {
        return {
          restrict: 'a',
          controller: function() {} // <--- anonymous controller
        };
      });
      

    • Alternative beside anonymous function as controller
      
      angular
      .controller('myCtrl', function() {})
      .directive('myDirective', function() {
        return {
          restrict: 'a',
          controller: 'myCtrl'
        };
      });
      
3) Testing AngularJS Directives

  • covered simple test of directive on
    • utilise jQlite 
    • unit test of directive's controller from one of the defined angular controller


Possible issue to overcome:

  1. To test a custom validation angular directive
    • unit test of form changes detection

1 comment:

  1. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.
    Surya Informatics

    ReplyDelete

Hey, thank you for spending time leaving some thoughts, that would be really helpful as encouragement for us to write more quality articles! Thank you!