Angular 7 : NullInjectorError for failing test, 服务在组件中仍然有效

标签 angular testing karma-jasmine

由于服务出现 NullInjector 错误,我的 Karma 测试失败。

  • 服务正在组件中工作(测试有问题,而不是组件有问题?),
  • 服务注入(inject)适用于其他组件,并且它们的测试通过

类似问题的解决方案与声明提供者有关。就我而言,我已经声明了一个提供者(见下文),并且该服务在组件内部工作。

Error: StaticInjectorError[LoginComponent -> AuthenticationProvider]: 
    NullInjectorError: No provider for AuthenticationProvider! 

服务:

@Injectable()
export class AuthenticationProvider {
  uri: string
  constructor(
    private http: HttpClient,
     private config: SancusConfiguration,
    ) 
    {

  }

失败的测试:

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ AppModule ],
      declarations: [  ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

我已在 NgModule 的提供程序中列出了 AuthenticationProvider:

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    ....
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    CollapseModule.forRoot(),
    ReactiveFormsModule,
    HttpClientModule
  ],
  schemas: [ NO_ERRORS_SCHEMA ],
  providers: [
  AuthenticationProvider,
   .....
  ],

  bootstrap: [AppComponent]
})
export class AppModule { }

最佳答案

  • 您必须在测试模块中列出您的提供程序,因为 AppModule 不会导出其提供程序。
  • 您也不应该加载整个 AppModule 来仅测试 LoginComponent
  • 您必须模拟这些提供商,因为它们看起来像是在进行网络调用。

代码示例:

TestBed.configureTestingModule({
  providers: [{provide: AuthenticationProvider,  useValue: mockProvider}, ... ],
  declarations: []
})

关于Angular 7 : NullInjectorError for failing test, 服务在组件中仍然有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55160959/

相关文章:

javascript - 根据对象数组中的属性过滤掉非空和未定义的项目

javascript - 类型错误 : 'undefined' is not a function (evaluating 'angular.element(window).width()' )

angular - 使用扩展面板对我的 Angular Material 数据表进行单元测试无法运行或检测不到动画完成?

html - 重新定位 Material 标签控件

javascript - 在 Angular 插值中使用 Array.map

angular - 如何在 Angular 5中删除后刷新页面

testing - 带有 Electron 的 TestCafe : Determine if app is visible on Windows desktop

testing - 函数调用中的测试或 clojure 中的语句未运行

ruby - Cucumber 是否支持元功能?

angular - 如何在Angular 7(或2+)中编写文件上传方法的单元测试