我正在嘗試測驗客戶驗證器,但我不斷收到此錯誤“無法讀取未定義的屬性(讀取 '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;
}
}
}
uj5u.com熱心網友回復:
您使測驗設定過于復雜。
因為FormValidationService它只是一個沒有依賴關系的類,你可以完全跳過使用,TestBed只做這樣的事情。
fdescribe('FormValidationService', () => {
let service: FormValidationService;
beforeEach(() => {
service = new FormValidationService();
});
...
});
在這種情況下,由于該類沒有內部狀態,您甚至可以洗掉beforeEach并只使用一次初始化該類const service = new FormValidationService();
干杯
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447688.html
