[英]How to test Angular functions that use http.get?
我完成了Angular英雄之旅,開始為它寫測試。 有些很容易編寫,但是當我嘗試從服務器獲取數據時,它就不起作用了。 我已經閱讀了有關測試 controller、defer、彈珠、調度程序之類的東西,但我仍然不知道如何進行。 我要么永久測試失敗,要么測試通過“SPEC HAS NO EXPECTATIONS”,這也沒有帶來任何結果,因為它本質上只是一個空測試。
//Test
it('#updateHero() works', waitForAsync(inject([HeroService], (service: HeroService) => {
let testHero = {
id: 42,
name: 'TestHero'
} as Hero
service.updateHero(testHero).subscribe()
service.getHero(42).subscribe(hero => expect(hero.name).toBe('TestHero'))
})));
//service
getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`
return this.http.get<Hero>(url).pipe(
tap(_ => this.messageService.add(`fetched hero id=${id}`)),
catchError(this.handleError<Hero>(`getHero id=${id}`)))}
updateHero(hero: Hero): Observable<any> {
return this.http.put(this.heroesUrl, hero, this.httpOptions).pipe(
tap(_ => this.messageService.add(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>('updateHero'))
)}
在其他一些測試中,我遇到了同樣的問題,他們只是沒有從我的服務中得到任何東西,但是實際的應用程序運行良好。
我的同事並沒有真正回答我的問題,除了一些奇怪的決定,比如 mocking 整個服務器響應。
經過很長時間嘗試我能找到的任何東西,我想出了以下解決方案:
...
beforeEach(async () => {
let router = {
snapshot: {
paramMap: {
get: () => 1, // represents the bookId
},
},
};
await TestBed.configureTestingModule({
declarations: [ DetailComponent ],
imports: [ HttpClientTestingModule ],
providers: [
{
provide: ActivatedRoute,
useValue: router
},
],
})
.compileComponents();
...
});
it('http.get hero works', () => {
const heroes: Hero[] = [
{ id: 1, name: 'Fake Batman1', imgSrc: '../assets/Batman.jpg', score: -5, commentary: 'FAKE!!!!!' },
{ id: 2, name: 'Fake Batman2', imgSrc: '../assets/Batman.jpg', score: -5, commentary: 'FAKE!!!!!' },
{ id: 3, name: 'Cool Batman', imgSrc: '../assets/Batman.jpg', score: 20, commentary: 'The coolest batman ever' },
{ id: 4, name: 'Fake Batman3', imgSrc: '../assets/Batman.jpg', score: -5, commentary: 'FAKE!!!!!' },
{ id: 5, name: 'Batman', imgSrc: '../assets/Batman.jpg', score: 3, commentary: 'No opinion' },
{ id: 6, name: 'Fake Batman4', imgSrc: '../assets/Batman.jpg', score: -5, commentary: 'FAKE!!!!!' },
]
const req = httpTestingController.expectOne('api/heroes/1');
expect(req.request.method).toEqual('GET');
req.flush(heroes[2]);
httpTestingController.verify();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.