Karma 测试 NullInjectorError: No provider for InjectionToken fileName

Кat*_*tya 5 unit-testing karma-jasmine angular

我知道 Stackoverflow 上有一些类似的问题,但它们并没有完全回答我的问题。

在我的 Angular 项目中运行 Karma 测试时,出现以下错误: NullInjectorError: No provider for InjectionToken app.config!

我知道在我的 .spec 文件中我需要为 InjectionToken 指定一个提供者,但我不确定确切的语法。

这是我的app.config文件:

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',
  ...
}
Run Code Online (Sandbox Code Playgroud)

然后在 .component.ts 文件中,我在构造函数中像这样使用它:

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

constructor(@Inject(APP_CONFIG) public appConfig) {}
Run Code Online (Sandbox Code Playgroud)

现在在这个组件的 .spec.ts 文件中,我知道我需要为 InjectionToken

我试着这样做:

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

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

但是这种语法不起作用,因为我还需要以某种方式在那里指定 app.conig 。任何帮助表示赞赏。谢谢

Кat*_*tya 9

在 *.spec.ts 文件中需要将以下内容添加到 providers 数组中:

providers: [
  { provide: APP_CONFIG, useValue: AppConfig }
]
Run Code Online (Sandbox Code Playgroud)