6: Get Data from a Server
[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   let scheduler: TestScheduler;
12
13   beforeEach(() =>  {
14     TestBed.configureTestingModule({
15       imports: [ HttpClientTestingModule ]
16     });
17     service = TestBed.inject(HeroService);
18     httpTestingController = TestBed.inject(HttpTestingController);
19     scheduler = new TestScheduler(((actual, expected) => {
20       expect(actual).toEqual(expected);
21     }));
22   });
23
24   afterEach(() => {
25     // After every test, assert that there are no more pending requests.
26     httpTestingController.verify();
27   });
28
29   it('should be created', () => {
30     expect(service).toBeTruthy();
31   });
32
33   it('get for id=0 should return an empty Observable', () => {
34     service.getHero(0).subscribe(fail, fail);
35
36     // HeroService should have made one request to GET heroes from expected URL
37     const req = httpTestingController.expectOne(`${service.heroesUrl}/0`);
38     expect(req.request.method).toEqual('GET');
39
40     // Respond with the mock heroes
41     req.flush('deliberate 404 error', {status: 404, statusText: 'Not Found'});
42   });
43
44   it('get for id=11 should return an Observable, that contains the hero with id 11', () => {
45     const expectedHero: Hero = {id: 11, name: 'Dr Nice'};
46
47     service.getHero(11).subscribe(
48       hero => expect(hero).toEqual(expectedHero, 'should return expected heroes'),
49       fail
50     );
51
52     // HeroService should have made one request to GET heroes from expected URL
53     const req = httpTestingController.expectOne(`${service.heroesUrl}/11`);
54     expect(req.request.method).toEqual('GET');
55
56     // Respond with the mock heroes
57     req.flush(expectedHero);
58   });
59 });