【发布时间】:2017-07-13 17:42:38
【问题描述】:
我正在为运行的 Angular 应用程序获取一组初始测试,但我遇到了其中一个依赖项的问题。查看测试规范的代码:
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { RouterModule, Routes } from '@angular/router';
import { Alert } from './models/alert.model';
import { AlertsService } from './services/alerts.service';
describe('AppComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent, NavbarComponent
],
imports: [
RouterModule,
],
providers: [
Alert, AlertsService
]
});
TestBed.compileComponents(); //This appears to be what throws the error
});
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app works!'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app works!');
}));
});
虽然有很多关于如何在 SO 上修复服务(尤其是路由)的讨论,但我还没有找到任何非常简单的类,比如下面的 Alert 文件:
export class Alert {
public static id: number = 0;
public message: string;
public id: number;
public type: string;
public dismissible: boolean;
public dismissOnTimeout: number;
constructor(config: any) {
this.message = config.message;
this.id = Alert.id && Alert.id++;
this.type = config.type || 'info';
this.dismissible = true;
this.dismissOnTimeout = settings.alertDismissOnTimeout;
}
}
此“模型”文件没有任何方法,仅作为警报的方便定义存在,您可以使用“new Alert(alert)”对其进行实例化。它由 AlertsService 使用,目前看来它正在工作,appComponent 的 HTML 引用 AlertsService 和一些实例化 Alert 对象的方法。到目前为止,一切都很好,但是当我尝试编译 AppComponent 时,我得到了标题中的错误。我尝试使用 Alert 类的存根,简化到其绝对最小值(基本上是一个空的构造函数),并且也返回相同的错误。
我(可能不正确)的理解是,我必须以某种方式将参数传递给警报对象,以使测试套件正常工作。由于其余代码的结构方式,我相当确定这不是循环依赖的问题,并且实际应用程序运行没有问题。这里的问题是我是否需要传入某种模拟参数,如果不需要,我该怎么做才能让这个规范正确编译?
【问题讨论】:
标签: angular unit-testing typescript karma-jasmine