繁体   English   中英

在 Angular 10 中运行单元测试时,APP_INITIALIZER 无法加载配置数据

[英]When running unit tests in Angular 10, APP_INITIALIZER fails to load config data

在 Angular 10 应用程序中,我使用 APP_INITIALIZER 从应用程序资产文件夹内的 config.json 文件加载配置文件数据。 我正在使用配置服务来获取此配置文件中的值。

app.module.ts 文件

@NgModule({
declarations: [AppComponent],
imports: [CommonModule, BrowserModule, AppRoutingModule, HttpClientModule],
providers: [
    {
      provide: APP_INITIALIZER,
      multi: true,
      deps: [ConfigService],
      useFactory: (configService: ConfigService) => {
        return () => {
          return configService.loadConfig();
        };
      }
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

配置.service.ts

@Injectable({
  providedIn: 'root'
})
export class ConfigService {
private appConfig: any;
error: any

constructor(private http: HttpClient) { }

    loadConfig() {
        return this.http.get('assets/config.json')
        .toPromise()
        .then(data => {
        this.appConfig = data;
       });
    } 

    get apiBaseUrl() {
       if (!this.appConfig) {
      throw Error('Config file not loaded!');
    }
   return this.appConfig.apiBaseUrl;
 }
}

当我为使用上述配置服务获取配置数据的服务之一运行单元测试时,测试失败,因为未加载配置文件中的数据。 我使用链接Angular APP_INITIALIZER 中提到的解决方法在测试中加载配置文件,如下所示,但仍未加载配置文件。

我的测试文件 product-list.service.spec.ts 中的 beforeEach 块是

    beforeEach(async () => {
        TestBed.configureTestingModule({
           imports: [HttpClientTestingModule],
           providers: [ProductListService]
        });

        await TestBed.inject(ApplicationInitStatus).donePromise; // <= Workaround fix which doesn't work

        httpTestingController = TestBed.inject(HttpTestingController);
        productListService= TestBed.inject(ProductListService);
    });

我不知道我是否遗漏了什么或以错误的方式做某事。 请帮我解决这个问题。

在文件 TestBed 中,您必须添加这样的提供程序:

// example with injected service
TestBed.configureTestingModule({
// Provide the service-under-test
providers: [
{
 provide: APP_INITIALIZER,
 multi: true,
 deps: [ConfigService],
 useFactory: (configService: ConfigService) => {
  return () => {
   return configService.loadConfig();
  };
 }
},
// add your services others
],
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM