首页 > 解决方案 > 角度控制匹配未知

问题描述

我有一个 Angular 自定义指令,如下所示:

import { ValidatorFn, AbstractControl } from '@angular/forms';

export function numericValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const testNumericPattern = '/^[0-9]{1,6}/g';
    if (!control.value) {
      return null;
    }
    const isValidNumeric = control.value.match(testNumericPattern);
    if (!isValidNumeric) {
      return { value: true };
    }
    return null;
  };

我的测试如下:

describe('NumericValidatorDirective', () => {
  const customNumber = new FormControl('', [numericValidator()]);

  it('should gives error when number is less than 0', () => {
    customNumber.patchValue(-1);
    expect(customNumber.valid).toBeFalsy();
  });

  fit('should gives error when a number is more than 999999', () => {
    customNumber.patchValue(999999);
    expect(customNumber.valid).toBeFalsy();
  });
});

但问题是,当我运行测试时,出现以下错误:

TypeError:control.value.match 不是函数

尽管我已经删除了检查if (!control.value) {,但我在测试时仍然遇到同样的问题。

知道为什么会出现这个问题,因为它对我来说似乎不合逻辑吗?

标签: angularangular-directive

解决方案


推荐阅读