簡體   English   中英

Angular 1.3 $ parser驗證方法未通過測試

[英]Angular 1.3 $parser validation method not passing test

最近,我們從Angular 1.2升級到1.3。 我們仍然必須支持IE8,因此請稍作調整,一切都可以正常進行。 但是,驗證器單元測試失敗時仍然存在一個奇怪的問題,但仍然可以在現實生活中使用。 另外,我將其移至$ validators也沒關系,它仍然不會通過。 將1.2放回Karma可以通過測試。

這不是主要問題,但是誰能告訴我下面的方法為什么在1.3中失敗但在1.2中失敗(並且可以正常工作)? 具體問題是正確設置了有效性,但是未提交$ viewValue,因此$ modelValue仍未定義(在我的測試中調用$ commitViewValue()和$ digest()不會執行任何操作,而且$ el.val(也不執行)。 ..); $ el.trigger(...))。

測試:

describe('Future date validation directive', function() {
    var $scope, $form;

    beforeEach(module('myapp'));
    beforeEach(inject(function($rootScope, $compile) {
        var $el = angular.element('<form name="form"><input type="date" name="future" ng-model="model.dt" future-date ng-model-options="{ updateOn: \'default\' }" /></form>');

        $scope = $rootScope.$new();
        $scope.model = {
            dt: null
        };

        $compile($el)($scope);
        $form = $scope.form;
    }));

    // This passes
    it('should fail if date is in the past', function() {
        var now = new Date().getTime();
        var day = 1000 * 60 * 60 * 24;
        var yesterday = new Date(now - day);

        $form.future.$setViewValue(yesterday, 'default');
        $scope.$digest();

        expect($scope.model.dt).toBeUndefined();
        expect($form.future.$valid).toBe(false);
    });

    // This fails
    it('should pass if date is in the future', function () {
        var now = new Date().getTime();
        var day = 1000 * 60 * 60 * 24;
        var tomorrow = new Date(now + day);

        $form.future.$setViewValue(tomorrow, 'default');
        $scope.$digest();

        expect($scope.model.dt).toEqual(tomorrow);
        expect($form.future.$valid).toBe(true);
    });
});

指令:

angular.module('myapp')
    .directive('futureDate', [function() {
        return {
            require: 'ngModel',
            link: function(scope, $elem, attrs, ctrl) {
                ctrl.$parsers.unshift(function (viewValue) {
                    var viewTicks = new Date(viewValue).getTime();
                    var currentTicks = new Date().getTime();

                    if (viewTicks > currentTicks) {
                        ctrl.$setValidity('futureDate', true);
                        return viewValue;
                    }

                    ctrl.$setValidity('futureDate', false);
                    return;
                });
            }
        };
    }]);

有任何想法嗎?

我想我已經解決了。 在Angular 1.3中,有一個內置的日期$ parser可以針對字符串YYYY-MM-DD驗證日期,因為我的規范正在傳遞實際的日期對象,但失敗了。 驗證指令在視圖中仍然有效,因為我的日期選擇器顯然正在傳遞字符串。 因此,更改規格會解決此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM