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;
13 TestBed.configureTestingModule({
14 imports: [ HttpClientTestingModule ],
15 providers: [ HeroService ]
17 service = TestBed.inject(HeroService);
18 httpTestingController = TestBed.inject(HttpTestingController);
22 // After every test, assert that there are no more pending requests.
23 httpTestingController.verify();
26 it('should be created', () => {
27 expect(service).toBeTruthy();
30 describe('#getHeroes', () => {
32 it('should return the expected heroes on success', () => {
34 const expectedHeroes: Hero[] = [{id: 11, name: 'Dr Nice'}];
36 service.getHeroes().subscribe(
37 heroes => expect(heroes).toEqual(expectedHeroes, 'should return expected heroes'),
41 const req = httpTestingController.expectOne(service.heroesUrl);
42 expect(req.request.method).toEqual('GET');
44 req.flush(expectedHeroes);
47 it('should return an empty list if the remote server fails', () => {
49 service.getHeroes().subscribe(
50 heroes => expect(heroes).toEqual([], 'should return an empty list'),
54 const req = httpTestingController.expectOne(service.heroesUrl);
55 expect(req.request.method).toEqual('GET');
57 // Respond with the mock heroes
58 req.flush('deliberate 500 error', {status: 500, statusText: 'Server Error'});
62 describe('#getHero', () => {
64 it('should return an empty observable for an invalid id', () => {
66 service.getHero(0).subscribe(fail, fail);
68 const req = httpTestingController.expectOne(`${service.heroesUrl}/0`);
69 expect(req.request.method).toEqual('GET');
71 req.flush('deliberate 404 error', {status: 404, statusText: 'Not Found'});
74 it('should return an observable with the requested hero for a valid id', () => {
76 const expectedHero: Hero = {id: 11, name: 'Dr Nice'};
78 service.getHero(11).subscribe(
79 hero => expect(hero).toEqual(expectedHero, 'should return expected heroes'),
83 const req = httpTestingController.expectOne(`${service.heroesUrl}/11`);
84 expect(req.request.method).toEqual('GET');
86 req.flush(expectedHero);