AngularJS单元测试需要模型的指令(使用Jasmine)

时间:2014-05-13 22:20:43

标签: angularjs unit-testing jasmine directive

我是使用茉莉花进行Anuglar JS单元测试的新手,我有一个需要模型的指令。以下是该指令的代码(它只在给定模型中提供数字之前附加$符号:

directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$formatters.unshift(function (value) {
                //return '$' + $filter(attrs.format)(ctrl.$modelValue);
                var num = $filter('currency')(ctrl.$modelValue);
                return num.split('.')[0];
            });

            ctrl.$parsers.unshift(function (viewValue) {
                var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                plainNumber = $filter('number')(plainNumber);
                var inputVal = plainNumber.indexOf('$') < 0 ? '$' + plainNumber : plainNumber;
                elem.val(inputVal);
                return plainNumber;
            });
        }
    };
}])

我一直在研究jamine我能够轻松地测试过滤器和控制器以及一些指令,但是这一个reuiqres模型所以我坚持它的任何建议?非常感谢您的建议(提前:))

祝你好运 Sajid

1 个答案:

答案 0 :(得分:1)

你应该写这样的测试:

it('tests this directive', inject(function($rootScope, $compile){
  var scope = $rootScope.$new();
  scope.myModelValue = 'something';
  var html = '<input format ng-model="myModelValue"></input>'

  var element = $compile(html)(scope);
  // I can't remember, but I think you need to call a scope.$apply() here
  // element.val() will return formatted value from the $parsers
  // Then element.val('something else') && scope.$apply() should change myModelValue from $formatters
}));