我有以下2个组件和一个由两者共享的单个服务。我需要单元测试它们,但我无法弄清楚如何测试服务对以下组件的依赖性。在Angular 2中测试API调用
//a.component.ts
import { Component, Input } from '@angular/core';
import { Http, Response } from '@angular/http';
import { SharedService } from './shared/shared.service';
@Component({
selector: 'a',
providers: [],
templateUrl: './a.component.html'
})
export class AComponent {
ax = {};
constructor(public helperService: SharedService) {
helperService.getFromAPI().subscribe(data => this.ax = data["people"]);
}
}
//b.component.ts
import { Component } from '@angular/core';
import { SharedService } from './shared/shared.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'b',
providers: [],
templateUrl: './b.component.html'
})
export class BComponent {
subscription: Subscription;
x = '';
constructor(public helperService: SharedService) {}
ngOnInit() {
this.subscription = this.helperService.c$.subscribe(
data => {
this.x = data;
});
}
}
这是调用API的服务。另一个功能setC
在点击按钮时将值添加到可观察值,并且该值将由BComponent
访问。
// shared.service
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
@Injectable()
export class SharedService {
private c = new Subject<string>();
c$ = this.c.asObservable();
constructor(
private http: Http
) { }
getFromAPI() {
return this.http.get('url')
.map((res: Response) => res.json());
}
setC(data: string) {
this.c.next(data);
}
}
我该如何在Jasmine中测试?到目前为止,我的努力是徒劳的。
我试着做这样
it('xxx', inject([SharedService], (service: SharedService) => {
const fixture = TestBed.createComponent(AComponent);
const app = fixture.componentInstance;
spyOn(service, 'c$').and.callThrough;
service.setC('Random Name');
expect(service.c$).toHaveBeenCalled();
}));
这种失败Expected spy c$ to have been called.
测试。
的[标签:angularjs]标签仅作角1.x中,对角2+使用标签:[tag:angular] – 0mpurdy