我花了大约 2 个小时试图解决这个问题。根据我的经验,您的 beforeEach() 函数中存在一些需要解决的问题。首先,您需要将 ReactiveFormsModule 导入到 TestBed 中,以便更改检测正确执行所有操作。其次,您需要在 beforeEach() 调用中手动运行 ngOnInit() 和 Fixture.DetectChanges() 来设置表单。请参阅下面的 beforeEach() 函数。我还包含了其他遇到此问题的人可能会发现相关的代码的其余部分。
组件模板:
<form [formGroup]='emailForm' (ngSubmit)='handleSubmit()'>
<div class='form-group'>
<label for='email'>Email address</label>
<input type='email' class='form-control' id='email' placeholder='Enter email'
formControlName='email'>
组件 TS:
constructor(
private apiService: ApiService,
private fb: FormBuilder,
private router: Router
) { }
ngOnInit() {
this.initializeForm();
}
initializeForm(): void {
this.formSubmitted = false;
this.serverProcessing = false;
this.emailForm = this.fb.group({
email: ['', Validators.compose([Validators.required, Validators.email])]
});
}
get email() {return this.emailForm.get('email');}
Spec TS 中的 beforeEach() 调用:
beforeEach(
async(() => {
apiServiceSpy = jasmine.createSpyObj('ApiService', ['sendResetPasswordEmail']);
routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);
TestBed.configureTestingModule({
declarations: [ SendPasswordResetEmailComponent ],
// Need to import this if we're messing with Reactive Form inputs!!
imports: [ReactiveFormsModule],
providers: [
{provide: ApiService, useValue: apiServiceSpy},
{provide: Router, useValue: routerSpy},
{provide: FormBuilder},
]
})
.compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(SendPasswordResetEmailComponent);
component = fixture.componentInstance;
// ngOnInit() doesn't get called automatically, so we have to do it ourselves
component.ngOnInit();
// Telling the fixture to detect changes is really important to correctly bind data
// Do this after calling ngOnInit() so changes propagate to the template
fixture.detectChanges();
});
测试规格样本:
it('should have an error for no username', () => {
const componentElement: HTMLElement = fixture.nativeElement;
const emailInput: HTMLInputElement = componentElement.querySelector('input');
emailInput.value = '@gmail.com';
emailInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.email.errors.email).toBeTruthy('@gmail.com valid');
});
it('should have no error if the email is valid', () => {
const componentElement: HTMLElement = fixture.nativeElement;
const emailInput: HTMLInputElement = componentElement.querySelector('input');
emailInput.value = '[email protected]';
emailInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.email.errors).toBeFalsy('[email protected] invalid');
});