import {fakeAsync, TestBed} from '@angular/core/testing'; import { ApiService } from './api.service'; import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; import {HttpClient} from '@angular/common/http'; import {of} from 'rxjs/internal/observable/of'; describe('ApiService', () => { let service: ApiService; const httpClientMock = { get: () => {}, post: () => {}, put: () => {}, delete: () => {}, } as any; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ {provide: String, useValue: ''}, {provide: HttpClient, useValue: httpClientMock} ] }); service = TestBed.inject(ApiService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call through to the httpClient when various REST calls are made', () => { const postSpy = spyOn(httpClientMock, 'post').and.returnValue(of({})); const getSpy = spyOn(httpClientMock, 'get').and.returnValue(of({})); const putSpy = spyOn(httpClientMock, 'put').and.returnValue(of({})); const deleteSpy = spyOn(httpClientMock, 'delete').and.returnValue(of({})); expect(postSpy).toHaveBeenCalledTimes(0); expect(getSpy).toHaveBeenCalledTimes(0); expect(putSpy).toHaveBeenCalledTimes(0); service.create('snacks'); service.getAll(); service.get('candy'); service.update({foo: 'bar'}, '1234', '2'); service.delete('candy'); expect(postSpy).toHaveBeenCalledTimes(1); expect(getSpy).toHaveBeenCalledTimes(2); expect(putSpy).toHaveBeenCalledTimes(1); expect(deleteSpy).toHaveBeenCalledTimes(1); }); it('should call update without a version tag', fakeAsync(() => { spyOn(httpClientMock, 'put').and.returnValue(of('put was called!')); service.update({foo: '123'}, 'foo') .subscribe(value => expect(value).toBe('put was called!')); })); it('should not put if resource is empty', fakeAsync(() => { service.update(null, 'foo') .subscribe(value => expect(value).toBe('Empty resource, nothing to put')); })); });