APP_INITIALIZER测试用例失败

时间:2019-02-20 16:53:36

标签: javascript angular karma-jasmine karma-runner angular-testing

我正在使用APP_INITIALIZER进行一些API调用,但一切正常,但添加了

 { provide: APP_INITIALIZER, useFactory: MyProviderFactory, deps: [MyService], multi: true }
app.module.ts中的

测试用例失败。 这是我的app.module.ts文件

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { LayoutModule } from '@angular/cdk/layout';

import { AppComponent } from './app.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// tslint:disable-next-line:max-line-length

import { MyService } from './services/my-provider.service';

export function MyProviderFactory(provider: MyService) {
  return () => provider.getdata();
}


@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    BrowserAnimationsModule,
    HttpClientModule,
    ReactiveFormsModule,
    RouterModule.forRoot([
      { path: '', component: AppComponent }
    ])
  ],
  providers: [ MyService,
              { provide: APP_INITIALIZER, useFactory: MyProviderFactory, deps: [MyService], multi: true }
            ],
  bootstrap: [AppComponent]
})
export class AppModule { }

这是错误

"message": "An error was thrown in afterAll\nFailed: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

还有如何在应用程序中测试APP_INITIALIZER。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

正如您的错误所说,您的工厂没有返回流(可观察,承诺,数组或可迭代)。相反,您要返回一个函数。

假设您的MyService.getdata()返回其中之一,则只需将其返回return provider.getdata()