我有以下两个组件和一个由双方共享的服务。我需要对它们进行单元测试,但是我无法知道如何测试服务对以下组件的依赖性。
//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);
}
}我怎么才能在茉莉花里测试这个?到目前为止,我的努力是徒劳的。
我试过这样做
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.进行测试。
发布于 2017-07-29 22:33:33
你似乎在监视一个Observable,但当你调用setC时,所称的是你的主体的next函数。所以你可能会想监视这个。
像spyOn(service.c, 'next').and.callThrough()这样的东西应该能起作用。
希望能帮上忙。
更新:如果您想要明确地测试您的Observable的功能,那么我只需订阅它,调用setC并测试响应,如下所示:
service.$c.subscribe((data) => {
expect(data).toBe('foobar');
});
service.setC('foobar');要在评论中回答您的问题:由于您的c是私有的,您可以像这样监视它:spyOn(service['c'], 'next').and.callThrough()。您的ide可能会唠叨着监视私有方法,在本例中,您可以添加如下的any类型:spyOn<any>(...)
https://stackoverflow.com/questions/45394625
复制相似问题