【问题标题】:AngularJS unit testing a Directive which requires model (Using Jasmine)AngularJS 单元测试需要模型的指令(使用 Jasmine)
【发布时间】:2014-07-01 19:06:11
【问题描述】:

我是使用 jasmine 进行 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 模型,所以我坚持下去有什么建议吗?非常感谢您的建议(提前:))

最好的问候 赛义德

【问题讨论】:

    标签: angularjs unit-testing jasmine directive


    【解决方案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
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 2013-08-25
      • 2015-01-18
      • 2013-08-29
      • 2016-09-28
      相关资源
      最近更新 更多