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

phy*_*boy 1 javascript typescript angular

当我尝试测试时,我遇到了错误...

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

应用程序模块.ts

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

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

    }));

}
Run Code Online (Sandbox Code Playgroud)

phy*_*boy 5

我发现我需要将 LoginComponent 放在declarations&providers部分中,从而成功解决了该问题。

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

    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
  }));
Run Code Online (Sandbox Code Playgroud)