2017-07-29 107 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