首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R3InjectorError(DynamicTestModule)[FormBuilder -> FormBuilder [:NullInjectorError:无FormBuilder提供者

R3InjectorError(DynamicTestModule)[FormBuilder -> FormBuilder [:NullInjectorError:无FormBuilder提供者
EN

Stack Overflow用户
提问于 2022-02-17 04:42:12
回答 3查看 4.8K关注 0票数 1

我在用茉莉花测试我的角码。我已经把所有东西都导入了,但仍然有错误。以下是两个错误:

NullInjectorError: R3InjectorError(DynamicTestModule)FormBuilder -> FormBuilder: NullInjectorError: FormBuilder没有提供者!被认为是真实的。

这些错误发生在多个组件上。我附上了带有这些错误的一个组件的示例。我该怎么解决呢?(我是初学者,所以请尽量用最简单的方式回答)

app.module.ts

代码语言:javascript
复制
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 { }

app.component.spec.ts

代码语言:javascript
复制
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!');
  });
});

reactFormComponent.html

代码语言:javascript
复制
<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>

reactFormComponent.ts

代码语言:javascript
复制
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'
    }
  };
}```
EN

回答 3

Stack Overflow用户

发布于 2022-02-17 05:05:43

错误指示在app.component.spec.ts中创建的测试模块找不到FormBuilder的提供程序。

FormBuilder是在FormsModule中定义的。您会注意到它是在AppModule中导入的(这就是为什么您的应用程序会编译和运行),但是它不是在configureTestingModuleapp.component.spec.ts中导入的。

修正:

代码语言:javascript
复制
describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FormsModule,               // << ----- add this line
        ReactiveFormsModule
      ],
票数 3
EN

Stack Overflow用户

发布于 2022-07-24 11:54:55

代码语言:javascript
复制
describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FormsModule,               // << ----- add this line
        ReactiveFormsModule        // You should add this too
      ],
票数 0
EN

Stack Overflow用户

发布于 2022-08-17 14:39:51

不是在app.component.spec.ts中,而是在<your-component-name>.spec.ts中,您必须添加以下内容:

代码语言:javascript
复制
        imports: [
            FormsModule,
            ReactiveFormsModule,
        ],
        providers: [<your-providers>],
        declarations: [<your-component-name>],
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71152614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档