Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Karma tests NullInjectorError: No provider for InjectionToken fileName

I know there are a few similar questions on Stackoverflow, but they don't quite answer my question.

When running Karma tests in my Angular project, I get this error: NullInjectorError: No provider for InjectionToken app.config!

I know that in my .spec file I need to specify a provider for InjectionToken, but I am not sure on exact syntax.

Here is my app.config file:

export let APP_CONFIG = new InjectionToken("app.config");
export const AppConfig: IAppConfig = {
  relativeDateLimit: 604800000,
  dateFormat: 'MM-DD-YYYY',
  ...
}
export const AppConfig: IAppConfig = {
  relativeDateLimit: 604800000,
  dateFormat: 'MM-DD-YYYY',
  ...
}

Then in the .component.ts file I use it like so in the constructor:

import { APP_CONFIG } from '../../app.config';

constructor(@Inject(APP_CONFIG) public appConfig) {}

Now in the .spec.ts file for this component I know that I need to set a provider for the InjectionToken

I tried doing it like so:

import { InjectionToken } from "@angular/core";
...

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ RelativeDateComponent ],
      providers: [ InjectionToken ]
    })
    .compileComponents();
  }));

But this syntax does not work, because I also need to specify app.congig there somehow. Any help is appreciated. Thanks

like image 683
Кatya Avatar asked Aug 17 '18 16:08

Кatya


1 Answers

In *.spec.ts file need to add the following to providers array:

providers: [
  { provide: APP_CONFIG, useValue: AppConfig }
]
like image 180
Кatya Avatar answered Oct 30 '22 22:10

Кatya