angular js指令茉莉的单位测试

时间:2016-08-19 10:24:26

标签: angularjs unit-testing jasmine

我已经编写了一个angular js指令的方法,但我不知道如何编写单元测试。

 var app = angular.module("myApp",[]);

 app.directive('minMax', function() {

    return {
        require: 'ngModel',
        link: function(scope, element, attr, mCtrl) {
            function myValidation(value) {
                if (value.toString().length > 2 & value.toString().length < 6) {
                    mCtrl.$setValidity('charE', true);
                } else {
                    mCtrl.$setValidity('charE', false);
                }
                return value;
            }
            mCtrl.$parsers.push(myValidation);
        }
    };
});

如何测试此方法?

1 个答案:

答案 0 :(得分:0)

看看这里:https://github.com/daniellmb/angular-test-patterns。 它包含大量测试模式。

指令测试示例:

describe('Directive: myDir', function () {
  var element, scope, compile, defaultData,
      validTemplate = '<my-dir ng-model="data"></my-dir>';

  function createDirective(data, template) {
    var elm;

    // Setup scope state
    scope.data = data || defaultData;

    // Create directive
    elm = compile(template || validTemplate)(scope);

    // Trigger watchers
    //scope.$apply();

    // Return
    return elm;
  }

  beforeEach(function () {

    // Load the directive's module
    module('myApp');

    // Reset data each time
    defaultData = 42;

    // Provide any mocks needed
    module(function ($provide) {
      //$provide.value('Name', new MockName());
    });

    // Inject in angular constructs otherwise,
    //  you would need to inject these into each test
    inject(function ($rootScope, $compile) {
      scope = $rootScope.$new();
      compile = $compile;
    });
  });

  describe('when created', function () {
    // Add specs
  });

  describe('when the model changes', function () {
    // Add specs
  });

  describe('when destroyed', function () {
    // Add specs
  });
});