Hello and thank you for your time:
I am trying to learn how to test a service which has a method to return an Observable.
I have done the Tour of heroes tutorial of the Angular page until the routing module, and I would like to unit test the code.
Here is the MyHeroService:
import {Injectable} from '@angular/core';
import {HEROES} from '../mock-heroes';
import {Hero} from '../Hero';
import {Observable} from 'rxjs/Observable';
import {of} from 'rxjs/observable/of';
import {MessageService} from '../message.service';
@Injectable()
export class MyHeroService {
getHeroes(): Observable<Hero[]> {
this.messageService.add('HeroService: fetched all your heroes');
return of(HEROES);
}
getHero(id: number): Observable<Hero> {
// Todo: send the message _after_ fetching the hero
this.messageService.add(`HeroService: fetched hero id=${id}`);
return of(HEROES.find(hero => hero.id === id));
}
constructor(private messageService: MessageService) {
}
}
And here is the unit test I am currently doing:
import {MyHeroService} from './my-hero.service';
import {MessageService} from '../message.service';
import {async, inject} from '@angular/core/testing';
describe('heroService', () => {
it('should return an Observable of Hero[]', async(() => {
const myHeroService = new MyHeroService(new MessageService([]));
myHeroService.getHero(1).subscribe(result => expect(result).toBeGreaterThan(0));
}));
});
The result which the test gives is:
I have also read: Unit testing an observable in Angular 2
Unit test 'success' and 'error' observable response in component for Angular 2
Angular 2 Observable Service Karma Jasmine Unit Test not working
Could you help me please to understand why it gives 'Expected undefined to be greater than 0.'