2017-07-29 110 views
3

我有以下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.测试。

+0

的[标签:angularjs]标签仅作角1.x中,对角2+使用标签:[tag:angular] – 0mpurdy

回答

3

您正在从事间谍活动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>(...)

+0

但'c'是'private'。我该如何监视它? –

+0

@SadarAli它本身并不回答你的问题,但[这个问题](https://stackoverflow.com/questions/12713659/typescript-private-members)可能会有所帮助 – 0mpurdy

+0

@SadarAli更新了我对该问题的回答 – lexith