2017-04-18 56 views
3

我一直在嘗試使用Jasmine爲Angular 2項目創建集成測試。我可以嘲笑服務和數據,並運行適當的單元測試,但現在我想測試以確保我的組件可以使用該服務實際連接到後端API。到目前爲止,我可以確認我的組件和服務中的方法是由我的間諜引發的,但是在組件內的.subscribe(....)方法直到測試完成/失敗之後纔會完成。我對我的規格代碼如下:Angular 2使用可觀測的組件測試組件而不嘲笑

import { async, ComponentFixture, TestBed, inject, fakeAsync } from '@angular/core/testing'; 
import { DebugElement } from "@angular/core"; 
import { By } from "@angular/platform-browser"; 

import { ReviewComponent } from './review.component'; 
import { FormsModule } from '@angular/forms'; 
import { UrlService } from 'app/shared/services/url.service'; 
import { HttpModule, Http } from '@angular/http'; 
import { ReviewService } from "./review.service"; 

describe('CommunicationLogComponent',() => { 
    let component: ReviewComponent; 
    let fixture: ComponentFixture<ReviewComponent>; 
    let serviceSpy: jasmine.Spy; 
    let componentSpy: jasmine.Spy; 
    let service: ReviewService; 

    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     imports: [FormsModule, HttpModule], 
     providers: [UrlService], 
     declarations: [ReviewComponent] 
    }) 
     .compileComponents(); 
    }); 

    beforeEach(() => { 
    fixture = TestBed.createComponent(ReviewComponent); 
    component = fixture.componentInstance; 
    component.processId = 6; 
    service = fixture.debugElement.injector.get(ReviewService); 
    componentSpy = spyOn(component, "ngOnInit").and.callThrough(); 
    serviceSpy = spyOn(service, 'getReviewByProcess').and.callThrough(); 
    }); 

    it('should create component',() => { 
    expect(component).toBeTruthy(); 
    }); 
    it('should not have called ngOnInit() yet',() => { 
    expect(componentSpy).not.toHaveBeenCalled(); 
    }); 

    it('should make a call to ngOnInit() and by extension getReviewByProcess',() => { 
    fixture.detectChanges(); 
    expect(componentSpy).toHaveBeenCalled(); 
    expect(serviceSpy).toHaveBeenCalled(); 
    }); 
    //ISSUES HERE 
    it('should show review after the getReviewByProcess resolves', async(() => { 
    fixture.detectChanges(); 
    fixture.whenStable().then(() => { 
     expect(componentSpy).toHaveBeenCalled(); 
     fixture.detectChanges(); 
     expect(component.Reviews[0]).not.toBe(undefined); 
    }); 
    }), 5000);   
}); 

所有的測試,直到一個標有「//問題對於這個問題」工作正常,並通過。

我正在使用async()並在試圖完成我的測試之前等待燈具變得穩定。它還通過componentSpy確認ngOnInit已被調用(它將連接到後端並訂閱Review)。

我的組件的代碼如下所示:

import { Component, EventEmitter, Input, OnInit } from '@angular/core'; 

//Service 
import { ReviewService } from "app/process/monitoring/shared/components/review/review.service"; 

//Classes 
import { Review } from "app/process/monitoring/shared/components/review/review"; 

@Component({ 
    providers: [ 
    ReviewService 
    ], 
    selector: 'monitoring-review', 
    templateUrl: './review.component.html', 
    styleUrls: ['./review.component.css'] 
}) 
export class ReviewComponent implements OnInit { 

    public Review: Review = new Review(); 
    public Reviews: Review[] = []; 

    @Input() public processId: number; 

    constructor(
    private ReviewService: ReviewService 
) { } 


    ngOnInit(): void { 
    this.ReviewService.getReviewByProcess(this.processId, true).first().subscribe(
     Reviews => { 
     if (Reviews) { 
      this.Reviews = Reviews //doesn't trigger until test is finished 
     } 
     }, 
     error => console.log(error) 
    ); 
    } 
} 

最後我ReviewService看起來是這樣的:

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Headers, RequestOptions, RequestMethod, URLSearchParams } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 

import 'rxjs/add/observable/throw'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/map'; 

// App-wide Services 
import { UrlService } from 'app/shared/services/url.service'; 

// Classes 
import { Review } from "app/process/monitoring/shared/components/review/review"; 


@Injectable() 
export class ReviewService { 

    private devUrl: string; 
    private jsonHeaders: Headers = new Headers({ 'Content-Type': 'application/json' }); 
    private prodUrl: string; 
    private reviewPath: string = 'monitoring/program/'; 

    constructor(
    private urlService: UrlService, 
    private http: Http 
) { 
    this.devUrl = this.urlService.getUrl('dev').url; 
    this.prodUrl = this.urlService.getUrl('prod').url; 
    } 

    getReviewByProcess(processId: number, isProd: boolean = false): Observable<Review[]> { 
    let targetUrl: string = (isProd ? this.prodUrl : this.devUrl) + this.reviewPath + "/" + processId; 

    return this.http.get(targetUrl, { withCredentials: true }) 
     .map((res: Response) => res.json()) 
     .catch((error: any) => Observable.throw(error.json().error || 'Server error') 
    ); 
    }; 
} 

使用噶調試器,我可以證實,我測試調用ngOnInit,然後調用該服務,但直到我的測試完成之後,它纔會觸及我的組件訂閱的內部部分(標記爲「//不觸發」)。

總結:我想創建一個測試,可以測試我的組件與我的服務集成,使用「實時」後端來收集我的數據。這是服務,我的組件不會嘲笑任何東西。我可以確認我的方法已經達到,但在ReviewComponent的ngOnInit()方法中找到的.subscribe(...)不會完成,直到測試完成/失敗。

回答

0

你需要你的服務來返回模擬數據。類似的東西:

spyOn(service, 'getReviewByProcess') 
    .and.returnValue(Observable.of(new Array<Review>())); 
+0

我不想從我的web API返回模擬數據,而是合法的數據。這只是茉莉花不能支持的東西,我應該尋找使用量角器的解決方案? – LandSharks

+0

這是單元測試,它應該被限定範圍並專用於特定的組件/功能,並且您需要模擬環境來對其進行存檔。如果你想模擬http,你可以使用MockBackend來模擬http服務級別。如果您需要給您打電話Web API以進行測試 - 使用Protractor進行端到端測試,但具有角度2單元測試的強大功能,我並不認爲e2e沒有太多需求。 –

+0

茉莉花不支持集成測試嗎?我注意到角度2的主要文檔視域:https://angular.io/docs/ts/latest/guide/testing.html#!#component-with-async-service 他們正在做的確切的事情我想要,但缺少一個http連接。那裏的數據是靜態的。 – LandSharks

2

您需要返回可觀察和測試中訂閱它的異步方法來等待它。例如,下面的假設測試會起作用。

it('', async(() => { 
    observable().subscribe(
    (review) => { 
     expect(component.Reviews[0]).not.toBe(undefined) 
    } 
) 
})); 

問題是您沒有等待異步調用在測試中執行。您可以稍微改變角度http服務,例如:

import { Http, HttpModule, BaseRequestOptions, XHRBackend, HttpModule, ConnectionBackend } from '@angular/http'; 
const httpSubject = new Subject() 
const http$ = httpSubject.asObservable() 
const httpFactory = (backend, options) => { 
    const newHttp = new Http(backend, options); 
    const helperHttp = new Http(backend, options); 
    newHttp.get = function(strng, options) { 
    return helperHttp.get(strng, options).do((response) => { 
     setTimeout(() => { 
     httpSubject.next({}); 
     }, 300); 
    }); 
    }; 
    return newHttp; 
} 

TestBed.configureTestingModule({ 
    imports: [HttpModule, FormModule], 
    providers: [ 
    UrlService, 
    ConnectionBackend, 
    BaseRequestOptions 
    { 
     provide: Http, 
     useFactory: httpFactory, 
     deps: [ XHRBackend, BaseRequestOptions] 
    } 
    ], 
    declarations: [ReviewComponent] 
}) 

it('should show review after the getReviewByProcess resolves', 
    async(() => { 
    http$.subscribe(() => { 
     expect(componentSpy).toHaveBeenCalled(); 
     expect(component.Reviews[0]).not.toBe(undefined); 
    }) 
    fixture.detectChanges(); 
})); 
+0

即使在放置適當的URL,選項等之後,您作爲示例設置的代碼也會出現調用堆棧錯誤。 – LandSharks

+0

@LandSharks對不起,我已更新它,它在本地爲我工作。給它一個去,如果你仍然有問題,我可以給你發送我創建的測試版本。 –

+0

@LandSharks請評論,如果你設法嘗試或找到另一種解決方案。這將是很好的知道。 –