jeudi 30 août 2018

Angular - Test component with custom injection - StaticInjectionError

I have an Angular library which gets configuration for an API with forRoot:

static forRoot(api: Api): ModuleWithProviders {
  return {
    ngModule: XyzModule,
    providers: [XyzComponent, { provide: 'API', useValue: api }]
  };

}

The module injects the object into the a component:

constructor(
  ...
  @Inject('API') private api: Api
) { }

This works very well when building the app or running it with ng serve.

However, when I try to test the component with ng test, I get the following error:

Error: StaticInjectorError(DynamicTestModule)[api]: 
  StaticInjectorError(Platform: core)[api]: 
    NullInjectorError: No provider for api!

The test file provides an Api object:

describe('XyzComponent', () => {
  beforeEach(async(() => {
    const api: Api = { url: 'http://localhost:8080' };
    TestBed.configureTestingModule({
      declarations: [ XyzComponent ],
      imports: [ ... ],
      providers: [
        { provide: 'API', useValue: api }
      ]
    })
    .compileComponents();
  }));
})

I already tried:

  • Replacing the string token with an InjectionToken
  • Using the inject() function for each test separately

.. but nothing works. Any ideas?

Aucun commentaire:

Enregistrer un commentaire