1 import { TestBed} from '@angular/core/testing';
2 import { TestScheduler } from 'rxjs/testing';
4 import { HeroService } from './hero.service';
5 import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
6 import { Hero } from './hero';
8 describe('HeroService', () => {
9 let service: HeroService;
10 let httpTestingController: HttpTestingController;
11 let scheduler: TestScheduler;
14 TestBed.configureTestingModule({
15 imports: [ HttpClientTestingModule ]
17 service = TestBed.inject(HeroService);
18 httpTestingController = TestBed.inject(HttpTestingController);
19 scheduler = new TestScheduler(((actual, expected) => {
20 expect(actual).toEqual(expected);
25 // After every test, assert that there are no more pending requests.
26 httpTestingController.verify();
29 it('should be created', () => {
30 expect(service).toBeTruthy();
33 it('get for id=0 should return an empty Observable', () => {
34 service.getHero(0).subscribe(fail, fail);
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');
40 // Respond with the mock heroes
41 req.flush('deliberate 404 error', {status: 404, statusText: 'Not Found'});
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'};
47 service.getHero(11).subscribe(
48 hero => expect(hero).toEqual(expectedHero, 'should return expected heroes'),
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');
56 // Respond with the mock heroes
57 req.flush(expectedHero);