【发布时间】:2016-11-11 16:22:57
【问题描述】:
您好,我正在尝试在 Angular2 中测试我的组件,但在尝试模拟我的服务时遇到了问题。我目前正在关注有关测试的 Angular2 文档。
我正在调用我从 Angular 服务构建的后端 API,只要我有 JWT 令牌,它就可以正常工作。 但是在测试方面,我只想在我的组件测试中模拟服务。
服务
@Injectable()
export class ItemService {
constructor(private _http: AuthHttp, private _store: Store<AppStore>) {}
items(): Observable<any[]> {
return this._http.get(ENDPOINT_ITEMS, {withCredentials: false})
.map((response: Response) => response.json().data);
}
}
组件
@Component({
selector: 'items',
template: require('./items.component.html'),
providers: [ItemService]
})
export class ItemsComponent {
items: Observable<Array<Object>>;
constructor(private _service: ItemService) {}
ngOnInit(): any {
this.items = this._service.items();
}
}
组件测试
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ ItemsComponent ],
providers: [
{ provide: ItemService, useValue: itemsMock },
]
});
fixture = TestBed.createComponent(ItemsComponent);
itemService = fixture.debugElement.injector.get(ItemService)
我希望我的模拟 ItemService 为我返回 useValue,itemsMock,以便我可以测试我的 html 标记是否具有正确的数据。 但看起来我的服务并没有被嘲笑对吧?
收到此错误:
错误:./ItemsComponent 类 ItemsComponent_Host 中的错误 - 内联模板:0:0 原因是:没有 AuthHttp 提供程序!在 karma.entry.js 中(第 17341 行)
【问题讨论】:
标签: unit-testing angular angular2-services angular2-testing