jeudi 14 mars 2019

Angular 7: NullInjectorError for failing test, service still works in component

I am have a failing Karma test due to a NullInjector error for a service.

  • The service IS working in the component (problem with test and not with component?),
  • the service injection works for other components, and their tests pass

Solutions to similar questions relate to declaring a provider. In my case I have declared a provider (see below), and the service works inside the component.

Error: StaticInjectorError[LoginComponent -> AuthenticationProvider]: 
    NullInjectorError: No provider for AuthenticationProvider! 

The service:

@Injectable()
export class AuthenticationProvider {
  uri: string
  constructor(
    private http: HttpClient,
     private config: SancusConfiguration,
    ) 
    {

  }

The failing test:

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

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

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

I have listed the AuthenticationProvider in providers in the NgModule:

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    ....
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    CollapseModule.forRoot(),
    ReactiveFormsModule,
    HttpClientModule
  ],
  schemas: [ NO_ERRORS_SCHEMA ],
  providers: [
  AuthenticationProvider,
   .....
  ],

  bootstrap: [AppComponent]
})
export class AppModule { }

Aucun commentaire:

Enregistrer un commentaire