Simplified tests for HeroService
[examples/angular-tour-of-heroes] / src / app / hero.service.spec.ts
1 import { TestBed} from '@angular/core/testing';
2 import { TestScheduler } from 'rxjs/testing';
3
4 import { HeroService } from './hero.service';
5 import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
6 import { Hero } from './hero';
7
8 describe('HeroService', () => {
9   let service: HeroService;
10   let httpTestingController: HttpTestingController;
11
12   beforeEach(() =>  {
13     TestBed.configureTestingModule({
14       imports: [ HttpClientTestingModule ],
15       providers: [ HeroService ]
16     });
17     service = TestBed.inject(HeroService);
18     httpTestingController = TestBed.inject(HttpTestingController);
19   });
20
21   afterEach(() => {
22     // After every test, assert that there are no more pending requests.
23     httpTestingController.verify();
24   });
25
26   it('should be created', () => {
27     expect(service).toBeTruthy();
28   });
29
30   describe('#getHeroes', () => {
31
32     it('should return the expected heroes on success', () => {
33
34       const expectedHeroes: Hero[] = [{id: 11, name: 'Dr Nice'}];
35
36       service.getHeroes().subscribe(
37         heroes => expect(heroes).toEqual(expectedHeroes, 'should return expected heroes'),
38         fail
39       );
40
41       const req = httpTestingController.expectOne(service.heroesUrl);
42       expect(req.request.method).toEqual('GET');
43
44       req.flush(expectedHeroes);
45     });
46
47     it('should return an empty list if the remote server fails', () => {
48
49       service.getHeroes().subscribe(
50         heroes => expect(heroes).toEqual([], 'should return an empty list'),
51         fail
52       );
53
54       const req = httpTestingController.expectOne(service.heroesUrl);
55       expect(req.request.method).toEqual('GET');
56
57       // Respond with the mock heroes
58       req.flush('deliberate 500 error', {status: 500, statusText: 'Server Error'});
59     });
60   });
61
62   describe('#getHero', () => {
63
64     it('should return an empty observable for an invalid id', () => {
65
66       service.getHero(0).subscribe(fail, fail);
67
68       const req = httpTestingController.expectOne(`${service.heroesUrl}/0`);
69       expect(req.request.method).toEqual('GET');
70
71       req.flush('deliberate 404 error', {status: 404, statusText: 'Not Found'});
72     });
73
74     it('should return an observable with the requested hero for a valid id', () => {
75
76       const expectedHero: Hero = {id: 11, name: 'Dr Nice'};
77
78       service.getHero(11).subscribe(
79         hero => expect(hero).toEqual(expectedHero, 'should return expected heroes'),
80         fail
81       );
82
83       const req = httpTestingController.expectOne(`${service.heroesUrl}/11`);
84       expect(req.request.method).toEqual('GET');
85
86       req.flush(expectedHero);
87     });
88   });
89 });