【发布时间】:2019-07-23 22:07:34
【问题描述】:
我是 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!');
});
});
【问题讨论】:
-
有助于查看您的
TestBed配置,但看起来您没有将SessionService放入配置对象的providers数组中。 -
您好,尝试将提供者添加到 spec.ts 文件中的提供者数组中。
-
@TheHeadRush 如果你说的是
TestBed配置对象,我没有——因为SessionService在项目中根本没有定义。它在正在导入的项目 LogoutComponent 中定义。 -
@JosefKatič 提供者(SessionService)不是来自这个项目——它来自另一个。如果我将它导入这个项目并将其放入 providers 数组中,Karma 只会大喊没有提供下一个服务(SessionServiceApi)等等。
-
您的设置实例化了多个组件。您要么需要将注入
TopNavComponent和LogoutComponent的所有服务添加到提供程序数组(使其成为集成测试),要么从declarations中删除额外的组件并将schema: [CUSTOM_ELEMENTS_SCHEMA]添加到配置中。跨度>
标签: javascript angular unit-testing frontend angular2-services