Angular 单元测试自定义验证器无法读取未定义的属性(读取 'dobLengthValidator')

Angular unit test custom validator Cannot read properties of undefined (reading 'dobLengthValidator')

我正在尝试测试客户验证器,但我一直收到此错误“无法读取未定义的属性(读取 'dobLengthValidator')”我一直在研究这个但似乎没有任何效果。验证器检查工作年限是否长于出生日期,如果是,则显示一条错误消息。还收到此错误“错误:模块 'DynamicTestModule' 导入的意外值 'DecoratorFactory'。请添加一个@NgModule 注释。'代码如下。

规格文件

import { Component, NgModule, Pipe } from '@angular/core';
import {TestBed, ComponentFixture} from '@angular/core/testing';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';

import {FormValidationService} from './form-validation.service';

fdescribe('FormValidationService', () => {
  
  
  let service;
  //let componentInstance: FormValidationService;
  beforeEach(async () =>  {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        ReactiveFormsModule,
        Component,
        Pipe
      ],
      providers: [
        FormBuilder
      ],
      declarations: [FormValidationService]
    }).compileComponents();
    
    service = TestBed.inject(FormValidationService);
    //componentInstance = service.componentInstance;
  });
  it('should be created', () => {
    expect(service).toBeTruthy();
  });
  it('check the validation for years in employment', () => {
    const dobLengthValidator = service.dobLengthValidator
    console.log(dobLengthValidator)
    const birthDate = new Date().setFullYear(1992, 6, 26).toString()
    expect(dobLengthValidator(birthDate, '3', '0')).toBeFalsy()
    expect(dobLengthValidator(birthDate, '40', '0')).toBeTruthy()
  })

});

组件文件

import {Injectable} from '@angular/core';
import {AbstractControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
import { CalculateStartDate } from '@app/utils';
import {environment} from '@environments/environment';
import { isBefore, isValid, subYears } from 'date-fns';
import { from } from 'rxjs';
import { Address } from '../models';

@Injectable({
  providedIn: 'root'
})
export class FormValidationService {


  dobLengthValidator = (dob: string, yrsFieldName: string, monthFieldName: string): ValidatorFn => {
    return (form: FormGroup) : ValidationErrors | null => {
      const yrs: string = !!yrsFieldName ? form.get(yrsFieldName)?.value ?? '0' : '0';
      const mths: string = !!monthFieldName ? form.get(monthFieldName)?.value ?? '0' : '0';
      const timeAliveTimestamp = new Date(dob).getTime();
      const timeEnteredTimestamp = new Date(CalculateStartDate(yrs, mths)).getTime();

      return timeAliveTimestamp >= timeEnteredTimestamp ? {dobLengthValidator: true} : null;
    }
  }

}

您使测试设置过于复杂。

因为 FormValidationService 只是一个没有依赖关系的 class,你可以完全跳过 TestBed 的使用,只做这样的事情。

fdescribe('FormValidationService', () => {
  let service: FormValidationService;
  
  beforeEach(() =>  {
    service = new FormValidationService();
  });

  ...

});

在这种情况下,由于 class 没有内部状态,您甚至可以删除 beforeEach 并使用 const service = new FormValidationService();[= 初始化 class 一次15=]

干杯