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 describe('#getHeroes', () => {
35 it('should return the expected heroes on success', () => {
37 const expectedHeroes: Hero[] = [{id: 11, name: 'Dr Nice'}];
39 service.getHeroes().subscribe(
40 heroes => expect(heroes).toEqual(expectedHeroes, 'should return expected heroes'),
44 const req = httpTestingController.expectOne(service.heroesUrl);
45 expect(req.request.method).toEqual('GET');
47 req.flush(expectedHeroes);
50 it('should return an empty list if the remote server fails', () => {
52 service.getHeroes().subscribe(
53 heroes => expect(heroes).toEqual([], 'should return an empty list'),
57 const req = httpTestingController.expectOne(service.heroesUrl);
58 expect(req.request.method).toEqual('GET');
60 // Respond with the mock heroes
61 req.flush('deliberate 500 error', {status: 500, statusText: 'Server Error'});
65 describe('#getHero', () => {
67 it('should return an empty observable for an invalid id', () => {
69 service.getHero(0).subscribe(fail, fail);
71 const req = httpTestingController.expectOne(`${service.heroesUrl}/0`);
72 expect(req.request.method).toEqual('GET');
74 req.flush('deliberate 404 error', {status: 404, statusText: 'Not Found'});
77 it('should return an observable with the requested hero for a valid id', () => {
79 const expectedHero: Hero = {id: 11, name: 'Dr Nice'};
81 service.getHero(11).subscribe(
82 hero => expect(hero).toEqual(expectedHero, 'should return expected heroes'),
86 const req = httpTestingController.expectOne(`${service.heroesUrl}/11`);
87 expect(req.request.method).toEqual('GET');
89 req.flush(expectedHero);