Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Yogendra0Sharma/d623652b854a4558a3454f15fc8a62e2 to your computer and use it in GitHub Desktop.

Select an option

Save Yogendra0Sharma/d623652b854a4558a3454f15fc8a62e2 to your computer and use it in GitHub Desktop.
Create angular directive with unit test

Basic directive

  • Run generator command yo angular:directive myDirective.
  • Run gulp test to ensure tests pass.

Refactor to handle passed-in objects

Given you want to pass in the following object {realName:'Steve Rogers', alias:'Captain America'}
  • Add scope property to the app/scripts/directives/mydirective.js file.
'use strict';

/**
 * @ngdoc directive
 * @name addressBookApp.directive:myDirective
 * @description
 * # myDirective
 */
angular.module('addressBookApp')
  .directive('myDirective', function () {
    return {
      template: '<div></div>',
      restrict: 'E',
      scope: { avenger: '=' }, // <--- ADD THIS SCOPE PROPERTY!
      link: function postLink(scope, element, attrs) {
        element.text('this is the myDirective directive');
      }
    };
  });
  • Refactor the template property to access the object.
'use strict';

/**
 * @ngdoc directive
 * @name addressBookApp.directive:myDirective
 * @description
 * # myDirective
 */
angular.module('addressBookApp')
  .directive('myDirective', function () {
    return {
      template: '<div>{{avenger.realName}} is {{avenger.alias}}</div>', // <--- Access properties here
      restrict: 'E',
      scope: { avenger: '=' },
      link: function postLink(scope, element, attrs) {
        // element.text('this is the myDirective directive'); <-- Comment this out
      }
    };
  });
  • Add a unit test.
'use strict';

describe('Directive: myDirective', function () {

  // load the directive's module
  beforeEach(module('addressBookApp'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
    scope.avenger = {realName:'Steve Rogers', alias:'Captain America'};
  }));

  it('should access the realName and alias properties', inject(function ($compile) {
    element = angular.element('<my-directive avenger="avenger"></my-directive>');
    element = $compile(element)(scope);
    scope.$digest();
    expect(element.text()).toBe('Steve Rogers is Captain America');
  }));
});
  • Run gulp test to ensure tests pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment