【发布时间】:2018-01-05 18:29:55
【问题描述】:
我有以下 2 个组件和一个由两者共享的服务。我需要对它们进行单元测试,但我无法弄清楚如何测试服务对以下组件的依赖性。
//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. 测试失败。
【问题讨论】:
标签: angular unit-testing jasmine spy