From: Kai Moritz Date: Sun, 10 May 2020 14:22:17 +0000 (+0200) Subject: HeroService returns an empty Observable, if the requested hero can't be found X-Git-Url: http://juplo.de/gitweb/?a=commitdiff_plain;h=ee578cce6211199049a491e3119deba48a484478;p=examples%2Fangular-tour-of-heroes HeroService returns an empty Observable, if the requested hero can't be found --- diff --git a/src/app/hero.service.spec.ts b/src/app/hero.service.spec.ts index 082791a..0ec21de 100644 --- a/src/app/hero.service.spec.ts +++ b/src/app/hero.service.spec.ts @@ -1,12 +1,35 @@ -import { TestBed } from '@angular/core/testing'; +import { TestBed} from '@angular/core/testing'; +import { TestScheduler } from 'rxjs/testing'; import { HeroService } from './hero.service'; +import { Hero } from './hero'; +import {map} from 'rxjs/operators'; describe('HeroService', () => { - beforeEach(() => TestBed.configureTestingModule({})); + let service: HeroService; + let scheduler: TestScheduler; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(HeroService); + scheduler = new TestScheduler(((actual, expected) => { + expect(actual).toEqual(expected); + })); + }); it('should be created', () => { - const service: HeroService = TestBed.get(HeroService); expect(service).toBeTruthy(); }); + + it('get for id=0 should return an empty Observable', () => + scheduler.run(({expectObservable}) => { + expectObservable(service.getHero(0)).toBe('(|)'); + }) + ); + + it('get for id=11 should return an Observable, that contains the hero with id 11', () => + scheduler.run(({expectObservable}) => { + expectObservable(service.getHero(11)).toBe('(a|)', { a: { id: 11, name: 'Dr Nice' }}); + }) + ); }); diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index 9003fe1..1db6072 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { Observable, of } from 'rxjs'; +import { Observable, of, EMPTY } from 'rxjs'; import { Hero } from './hero'; import { HEROES } from './mock-heroes'; import { MessageService } from './message.service'; @@ -19,6 +19,11 @@ export class HeroService { getHero(id: number): Observable { this.messageService.add(`HeroService: fetched hero id=${id}`); - return of(HEROES.find(hero => hero.id === id)); + const found: Hero | undefined = HEROES.find(hero => hero.id === id); + if (found === undefined) { + return EMPTY; + } else { + return of(found); + } } }