ngModel指令的单元测试不起作用

时间:2020-07-24 21:45:02

标签: angularjs typescript unit-testing jasmine

我有一条指令,该指令应用正则表达式清除文本输入中的任何值(例如Johnwww.应该将模型值更新为John)。

指令:

export default function ValidateSenderUsernameDirective(): 
IDirective<ValidateSenderUsernameDirectiveScope>  {
    return {
        restrict: 'A',
        scope: {},
        require: 'ngModel',
        link (scope: IScope, iElement: JQLite, iAttrs: IAttributes, ngModelCtrl: INgModelController): void {

            function cleanInput (input: string): string {
                if (!input) { return ''; }

                const pattern: RegExp =
                /[^A-Za-z0-9!@$*,./:=àâäèéêëîïôoeùûu^̈ÿçÀÂÄÈÉÊËÎÏÔOEÙÛÜŸÇ]|(https:|http:|www\.)/;
                const validatedInput: string = input.replace(pattern, '');

                if (input !== validatedInput) {
                    ngModelCtrl.$setViewValue(validatedInput);
                    ngModelCtrl.$render();
                }
                return validatedInput;
            }

            ngModelCtrl.$parsers.push((viewVal: string) => {
                return cleanInput(viewVal);
            });
        }
    };
}

测试:

describe('cleanInput', () => {
    let scope: IDirectiveScope;

    beforeEach(angular.mock.module(directiveModule));
    beforeEach(angular.mock.inject(function($compile: ICompileService, $rootScope: IRootScopeService): void {
        scope = $rootScope.$new() as IDirectiveScope;
        const input: JQLite = $compile('<input type="text" ng-model="modelVal" validate-sender-username/>')(scope);
    }));

    it('should properly clean "Johnwww."', () => {
        const result: string = 'John';

        scope.modelVal = 'Johnwww.';
        scope.$apply();
        expect(scope.modelVal).toEqual(result);
    });
});

为清楚起见,IDirectiveScope扩展了IScope,因为我需要定义modelVal属性

export interface IDirectiveScope extends angular.IScope {
    modelVal: string;
}

我收到错误Expected 'Johnwww.' to equal 'John'.scope.modelVal$scope.apply()期间未更新。我在这里想念什么?

0 个答案:

没有答案
相关问题