Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: StaticInjectorError[FormBuilder] when running ng test

Tags:

angular

I have just started using ng test to verify my Angular app. I used Angular-Cli to generate my modules and components and the .spec.ts were straight out of the box.

I am getting the following on one test:

Error: StaticInjectorError[FormBuilder]:
StaticInjectorError[FormBuilder]: NullInjectorError: No provider for FormBuilder!

The component it fails on has these declared

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

And my constructor just news up a FormBuilder

constructor(private fb: FormBuilder) { }

I also have the form builder declared in my app.module

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
 imports: [
    BrowserModule,
    AdminModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    FormBuilder,
    HttpModule,
    NgbModule.forRoot()

Test code

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { CreatearchiveComponent } from './createarchive.component';
import { NO_ERRORS_SCHEMA } from '@angular/core';

describe('CreatearchiveComponent', () => {
  let component: CreatearchiveComponent;
  let fixture: ComponentFixture<CreatearchiveComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CreatearchiveComponent ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CreatearchiveComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
like image 722
Ross Avatar asked Nov 18 '17 23:11

Ross


1 Answers

Your test uses a testing angular module which only has a CreatearchiveComponent, but doesn't import ReactiveFormsModule. So the FormBuilder service, provided by ReactiveFormsModule, is not available. You need to import the modules that are needed by the component under test:

TestBed.configureTestingModule({
  declarations: [ CreatearchiveComponent ],
  imports: [ReactiveFormsModule],
  schemas: [NO_ERRORS_SCHEMA]
})
like image 168
JB Nizet Avatar answered Jan 03 '23 20:01

JB Nizet