【发布时间】:2017-10-17 05:40:58
【问题描述】:
我正在尝试使用测试用例覆盖组件中的服务调用,如下所述。
但是在运行ng test 时出现错误,如下所示:
失败:this.monthService.getMonthView(...).then 不是函数 TypeError: this.monthService.getMonthView(...).then 不是函数
服务: (MonthService.ts)
getMonthView是MonthService里面的服务调用
getMonthView(forecastMonth: string): Promise<any[]> {
const options = new RequestOptions({ headers: this.headers });
const url = this.BaseUrl + forecastMonth;
return this.http.get(url, options)
.toPromise()
.then(response => response.json() as any[])
.catch(this.handleError);
}
组件: (MonthComponent.ts)
MonthService被导入并注入MonthComponent.ts
loadDataOnMonthViewClicked(forecastMonth) {
this.monthService.getMonthView(forecastMonth)
.then(response =>
this.result = response
);
}
测试套件:
beforeEach(() => {
/**
* Ref:https://angular.io/guide/testing#!#component-fixture
*/
fixture = TestBed.createComponent(MonthComponent);
component = fixture.componentInstance;
myService = TestBed.get(MonthService );
//fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
fit('should test loadDataOnMonthViewClick', async(() => {
let data=["10","20","30"];
spyOn(component.monthService, 'getMonthView').and.returnValue(result);
component.loadDataOnMonthViewClicked('Jan');
fixture.detectChanges();
expect(component.result).toBe(data);
}));
【问题讨论】:
标签: javascript angular jasmine karma-jasmine