NullInjectorError:StaticInjectorError(DynamicTestModule)在Angular 2中进行测试时

问题描述 投票:1回答:1

我是Angular2的新手,并尝试在app.component.spec.ts文件中编写测试。我的应用程序相对简单,除了从第三方库(由同事编写)导入LoginComponent和LogoutComponent之外。这些组件现在分别用于路由登录或注销,非常简单。运行ng serve编译好,应用程序“顺利”运行。但是,运行ng test会给我这个错误:

NullInjectorError: StaticInjectorError(DynamicTestModule)[LogoutComponent -> SessionService]: 
  StaticInjectorError(Platform: core)[LogoutComponent -> SessionService]: 
    NullInjectorError: No provider for SessionService!

LogoutComponent是从其他项目导入的。这个错误是否意味着我需要进入该项目并进行一些更改,或者我应该在我的项目中以某种方式嘲笑SessionService?

规格代码:

import {} from 'jasmine';
import {async, TestBed} from '@angular/core/testing';
import {RouterTestingModule} from '@angular/router/testing';
import {AuthErrorStateService, LogoutComponent} from '@custom-library';

import {AppComponent} from './app.component';
import {AppErrorStateService} from './core/error-states/app-error-state.service';
import {TopNavComponent} from './core/top-nav/top-nav.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed
        .configureTestingModule({
          imports: [RouterTestingModule],
          providers: [
            AppErrorStateService, AuthErrorStateService
          ],
          declarations: [AppComponent, TopNavComponent, LogoutComponent],
        })
        .compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'My App'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('My App');
  });

  it('should render title in a h1 tag', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toEqual('Welcome to My App!');
  });
});
javascript angular unit-testing frontend angular2-services
1个回答
1
投票

问题是在TestBed中声明了多个组件,就像这样

 declarations: [AppComponent, TopNavComponent, LogoutComponent]

当测试调用compileComponents()时,会导致多个组件被实例化。当发生这种情况时,declarations数组中的每个组件都需要在providers数组中声明的依赖项才能完成实例化。其中一个声明的组件取决于SessionService,但该服务不在提供程序中,因此您获得NullInjectorError

有两种解决方案:

  • 只在declarations数组中声明一个组件并将schemas: [ CUSTOM_ELEMENTS_SCHEMA ]添加到TestBed配置对象
  • 继续声明多个组件并将每个组件的所有依赖项(或其模拟)添加到providers数组
© www.soinside.com 2019 - 2024. All rights reserved.