Karma tests NullInjectorError: No provider for InjectionToken fileName

12,674

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

providers: [
  { provide: APP_CONFIG, useValue: AppConfig }
]
Share:
12,674

Related videos on Youtube

Кatya
Author by

Кatya

Updated on June 08, 2022

Comments

  • Кatya
    Кatya about 2 years

    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

  • OmGanesh
    OmGanesh over 4 years
    Isn't this concept should apply for the service injection also... For my case it is the mock class to use. As mentioned above, I am using { provide: Token.MyServiceInterface, useClass: MockMyServiceInterface } It is throwing same error: "NullInjectorError: No provider for Injection Token Token.MyServiceInterface!"