Rya*_*zel 10 javascript frontend unit-testing angular2-services angular
我是 Angular2 的新手,并试图在app.component.spec.ts文件中编写一个测试。我的应用程序相对简单,除了它从 3rd 方库(由同事编写)导入 LoginComponent 和 LogoutComponent 之外。这些组件现在分别用于路由登录或注销,非常简单。运行ng serve编译正常,应用程序“平稳”运行。ng test然而,Running给了我这个错误:
NullInjectorError: StaticInjectorError(DynamicTestModule)[LogoutComponent -> SessionService]:
StaticInjectorError(Platform: core)[LogoutComponent -> SessionService]:
NullInjectorError: No provider for SessionService!
Run Code Online (Sandbox Code Playgroud)
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!');
});
});
Run Code Online (Sandbox Code Playgroud)
The*_*ush 17
问题是TestBed像这样声明多个组件
declarations: [AppComponent, TopNavComponent, LogoutComponent]
Run Code Online (Sandbox Code Playgroud)
导致在测试调用时实例化多个组件compileComponents()。发生这种情况时,declarations数组中的每个组件都需要在providers数组中声明其依赖项才能完成实例化。声明的组件之一依赖于SessionService,但该服务不存在于提供者中,因此您将获得NullInjectorError.
对此有两种解决方案:
declarations数组中声明一个组件并添加
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]到TestBed配置对象中providers数组中| 归档时间: |
|
| 查看次数: |
28024 次 |
| 最近记录: |