NullInjectorError:没有自定义组件的提供程序-添加到提供程序不起作用

时间:2018-07-24 14:46:47

标签: javascript angular typescript

尝试测试时抛出错误...

我已经阅读了许多类似的相关问题,但是将我的自定义LoginComponent添加到app.module.ts提供程序没有帮助吗?它已经在导入部分。

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AppHttpInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

login.component.spec.ts (概述)

import {async, ComponentFixture, inject, TestBed} from '@angular/core/testing';

import {LoginComponent} from './login.component';
import {FormsModule, NgForm} from '@angular/forms';
import {HttpClientModule} from "@angular/common/http";
import {AuthService} from "../../services/auth/auth.service";

describe('LoginComponent', () => {
   beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LoginComponent],
      imports: [FormsModule, HttpClientModule, FormsModule]
    }).compileComponents();

    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
  }));

    it('Attempt login with various invalid forms', 
      inject([LoginComponent, AuthService],
      (loginComp: LoginComponent, authServ: AuthService) => {

    // Testing stuff here

    }));

}

1 个答案:

答案 0 :(得分:0)

我设法发现需要将LoginComponent放在declarationsproviders部分中,从而解决了该问题。

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

    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
  }));