Nullinjectorerror: no provider for FormBuilder (I'm importing ReactiveFormsModule)

35,457

Solution 1

Open app.component.spec.ts and add ReactiveFormsModule to imports array.

app.component.spec.ts

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule <================================= add this
      ],
      declarations: [
        AppComponent,
        HoursCalculatorComponent
      ],
    }).compileComponents();
  }));

Solution 2

In the ngModule need to import the formModule

  imports: [ 
      FormsModule,
      ReactiveFormsModule,
  ],

import that on the unit test also,

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
          ReactiveFormsModule,
          FormsModule,
      ],
      declarations: [ HoursCalculatorComponent ]
    }).compileComponents();
  }));

Solution 3

In the ngModule need to import the ReactiveFormsModule from @angular/forms:

import { ReactiveFormsModule } from '@angular/forms';

And add ReactiveFormsModule under imports:

imports: [ReactiveFormsModule]

Solution 4

In latest version of Angular I was still facing this issue even after importing ReactiveFormsModule in the form page unless I imported the same ReactiveFormsModule in main app.module.ts file as well.

Share:
35,457

Related videos on Youtube

Sophie McCall
Author by

Sophie McCall

Updated on July 09, 2022

Comments

  • Sophie McCall
    Sophie McCall almost 2 years

    So I'm trying to write a really basic test for a component. I just want to make sure that the form that I'm creating using FormBuilder is an instance of FormGroup, but I'm consistently getting a NullInjectorerror: No provider for FormBuilder, and I've tried pretty much everything. I made sure I was importing the ReactiveFormsModule.

    hours-calculator.component.ts

    import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormBuilder } from '@angular/forms';
    
    @Component({
      selector: 'app-hours-calculator',
      templateUrl: './hours-calculator.component.html',
      styleUrls: ['./hours-calculator.component.scss']
    })
    export class HoursCalculatorComponent implements OnInit {
    
      constructor(private formBuilder: FormBuilder) { }
    
      form: FormGroup;
      
      ngOnInit() {
          this.form = this.formBuilder.group({
             control1: this.formBuilder.control('')
          });
      }
    }

    hours-calculator.spec.ts

    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { FormGroup, ReactiveFormsModule, FormsModule, FormBuilder } from '@angular/forms';
    import { HoursCalculatorComponent } from './hours-calculator.component';
    
    describe('HoursCalculatorComponent', () => {
      let component: HoursCalculatorComponent;
      let fixture: ComponentFixture<HoursCalculatorComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [
            FormsModule,
            ReactiveFormsModule
          ],
          declarations: [ HoursCalculatorComponent ]
        }).compileComponents();
      }));
    
      beforeEach(() => {
        fixture =   TestBed.createComponent(HoursCalculatorComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create a form using formbuilder', () => {
        expect(component.form instanceof FormGroup).toBeTruthy();
      });
    }

    Am I just missing something extremely obvious? I'm really tearing my hair out over this one. I'm really new to unit testing angular components, so explain it to me like I'm 5 :) For the record, I'm using angular 7.

    Full error message:

              StaticInjectorError(Platform: core)[HoursCalculatorComponent -> FormBuilder]: 
                NullInjectorError: No provider for FormBuilder!
                at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3228:1)
                at resolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3473:1)
                at tryResolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3417:1)
                at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3314:1)
                at resolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3473:1)
                at tryResolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3417:1)
                at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3314:1)
                at resolveNgModuleDep (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:19784:1)
                at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:20473:1)
                at resolveDep (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:20844:1)
    

    package.json

        {
          "name": "babysitter-app",
          "version": "0.0.0",
          "scripts": {
            "ng": "ng",
            "start": "ng serve",
            "build": "ng build",
            "test": "ng test",
            "lint": "ng lint",
            "e2e": "ng e2e"
          },
          "private": true,
          "dependencies": {
            "@angular/animations": "~7.1.0",
            "@angular/common": "~7.1.0",
            "@angular/compiler": "~7.1.0",
            "@angular/core": "~7.1.0",
            "@angular/forms": "~7.1.0",
            "@angular/platform-browser": "~7.1.0",
            "@angular/platform-browser-dynamic": "~7.1.0",
            "@angular/router": "~7.1.0",
            "core-js": "^2.5.4",
            "rxjs": "~6.3.3",
            "tslib": "^1.9.0",
            "zone.js": "~0.8.26"
          },
          "devDependencies": {
            "@angular-devkit/build-angular": "~0.11.0",
            "@angular/cli": "~7.1.3",
            "@angular/compiler-cli": "~7.1.0",
            "@angular/language-service": "~7.1.0",
            "@types/node": "~8.9.4",
            "@types/jasmine": "~2.8.8",
            "@types/jasminewd2": "~2.0.3",
            "codelyzer": "~4.5.0",
            "jasmine-core": "~2.99.1",
            "jasmine-spec-reporter": "~4.2.1",
            "karma": "~3.1.1",
            "karma-chrome-launcher": "~2.2.0",
            "karma-coverage-istanbul-reporter": "~2.0.1",
            "karma-jasmine": "~1.1.2",
            "karma-jasmine-html-reporter": "^0.2.2",
            "protractor": "~5.4.0",
            "ts-node": "~7.0.0",
            "tslint": "~5.11.0",
            "typescript": "~3.1.6"
          }
        }
    
    • yurzui
      yurzui about 5 years
      Can you post the full error message?
    • Sophie McCall
      Sophie McCall about 5 years
      @yurzui edited to include error message
    • yurzui
      yurzui about 5 years
      Your code works for me. Please create simple github repo to reproduce your issue
    • Sophie McCall
      Sophie McCall about 5 years
    • yurzui
      yurzui about 5 years
      I don't see HoursCalculatorComponent there
    • Sophie McCall
      Sophie McCall about 5 years
      I've added the FormsModule to the testmodule imports locally, and am getting the same error, just FYI
    • Sophie McCall
      Sophie McCall about 5 years
      my bad, I hadn't pushed my local changes, should be there now
  • Sophie McCall
    Sophie McCall about 5 years
    THAT DID IT. Thank you so much. I was under the impression that the spec files for other files didn't matter, since you're configuring a test module anyway. Thanks for the help
  • yurzui
    yurzui about 5 years
    You're welcome! Please consider accepting the answer.
  • user
    user over 4 years
    I had a similar situation to the posted question, tried a bunch of different examples and other stack overflow queries, this is the one that did it for me. Also, I'm using angular 8