我正在使用Jasmine测试我的Angular 代码。我已经导入了所有内容,但仍然出现错误。以下是2个错误:
空注入器错误:R3注入器错误(动态测试模块)[表单生成器-〉表单生成器]:空注入器错误:没有FormBuilder的提供程序!
预期undefined为真实值。
这些错误在多个组件上。我附上了一个有这些错误的组件的示例。我如何解决它?(我是一个初学者,所以请尝试用最简单的方式回答它)
应用程序模块.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {FormsModule } from '@angular/forms';
import { SortPipe } from './sort.pipe';
import { CustomPipeComponent } from './custom-pipe/custom-pipe.component';
import { CustpipeComponent } from './custpipe/custpipe.component';
import { RideFilterPipePipe } from './ride-filter-pipe.pipe';
import { ReactFormComponent } from './react-form/react-form.component';
import { TemplateDrivenFormComponent } from './template-driven-form/template-driven-form.component';
import { EmailValidator } from './template-driven-form/emailValidator';
@NgModule({
declarations: [
AppComponent,
SortPipe,
CustomPipeComponent,
CustpipeComponent,
RideFilterPipePipe,
ReactFormComponent,
TemplateDrivenFormComponent,
EmailValidator
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
应用程序组件规范ts
import { TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule,
ReactiveFormsModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'carpool'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('carpool');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.content span')?.textContent).toContain('carpool app is running!');
});
});
React表单组件.html
<div class="login-comp">
<div class="container">
<div class="outer-box">
<h3 class="title">Reactive form</h3>
<form [formGroup]="registerForm">
<div class="form-group">
<label class="">Name</label>
<input class=" form-control" type="text" formControlName="firstName">
<p *ngIf="(registerForm.get('firstName')?.dirty ||
registerForm.get('firstName')?.touched ) &&
registerForm.get('firstName')?.errors "
class="alert alert-danger">This is required</p>
</div>
<div class="form-group">
<label class="">email</label>
<input class=" form-control" type="email" formControlName="email">
<p *ngIf="(registerForm.get('email')?.dirty ||
registerForm.get('email')?.touched ) &&
registerForm.get('email')?.errors "
class="alert alert-danger">invalid</p>
</div>
<div class="form-group">
<fieldset formGroupName="address">
<label class="">Steet</label>
<input class=" form-control" type="text" formControlName="street">
<label class="">Zip</label>
<input class=" form-control" type="text" formControlName="zip">
<label class="">City</label>
<input class=" form-control" type="text" formControlName="city">
</fieldset>
</div>
<button type="submit" [disabled]="!registerForm.valid" class="btn btn-primary" (click)="subForm()">Submit</button>
</form>
<div [hidden]="!submittedForm">
<p>Name: {{registerForm.get('firstName')?.value}}</p>
<p>Name: {{registerForm.get('email')?.value}}</p>
<p>Street: {{registerForm.get('address.street')?.value}}</p>
<p>City: {{registerForm.get('address.city')!.value}}</p>
<p>zip: {{registerForm.get('address.zip')!.value}}</p>
</div>
</div>
</div>
</div>
React表单组件.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-react-form',
templateUrl: './react-form.component.html',
styleUrls: ['./react-form.component.css']
})
export class ReactFormComponent implements OnInit {
registerForm!:FormGroup;
submittedForm!:boolean;
constructor(private formBuilder:FormBuilder) {}
ngOnInit(): void {
this.registerForm=this.formBuilder.group({
firstName: ['',Validators.required],
email: ['', validateEmail],
address: this.formBuilder.group({
street:[],
zip:[],
city:['',Validators.required]
})
});
}
subForm() {
this.submittedForm=true;
console.log(this.registerForm);
}
}
function validateEmail(eid:FormControl):any {
let email_regex=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return email_regex.test(eid.value)?null : {
emailInvalid: {
message: 'Invalid Format'
}
};
}```
3条答案
按热度按时间ccrfmcuu1#
该错误指示在
app.component.spec.ts
中创建的测试模块找不到FormBuilder
的提供程序。FormBuilder
在FormsModule
中定义。您会注意到,它在AppModule
中导入(这就是您的应用编译和运行的原因),但在app.component.spec.ts
中的configureTestingModule
中没有导入。修复:
myzjeezk2#
baubqpgj3#
不是在
app.component.spec.ts
中,而是在<your-component-name>.spec.ts
中,您必须添加以下内容: