From 10bea2311ebbab0884e1f700f56514b4a8609463 Mon Sep 17 00:00:00 2001 From: "fabio.formosa" Date: Tue, 27 Oct 2020 00:30:39 +0100 Subject: [PATCH] #26 added unit test for api.service.ts --- .../src/app/services/api.service.spec.ts | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 quartz-manager-frontend/src/app/services/api.service.spec.ts diff --git a/quartz-manager-frontend/src/app/services/api.service.spec.ts b/quartz-manager-frontend/src/app/services/api.service.spec.ts new file mode 100644 index 0000000..b3ce83f --- /dev/null +++ b/quartz-manager-frontend/src/app/services/api.service.spec.ts @@ -0,0 +1,75 @@ +import { TestBed } from "@angular/core/testing"; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { ApiService } from './api.service'; +import { HttpClient, HttpHeaders } from '@angular/common/http'; + +class Data{ + name: string +} + +class HttpResponseMock { + constructor( + public body: unknown, + public opts?: { + headers?: + | HttpHeaders + | { + [name: string]: string | string[]; + }; + status?: number; + statusText?: string; + } + ) {} + } + +describe('ApiServiceTest', () => { + + let apiService: ApiService; + let httpClient: HttpClient; + let httpTestingController: HttpTestingController; + + const SAMPLE_URL = '/sample-url'; + const URL_401 = '/url-response-401'; + const testData: Data = {name: 'Test Data'}; + + beforeEach(() => { + + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + providers: [ApiService] + }); + apiService = TestBed.inject(ApiService); + + httpClient = TestBed.inject(HttpClient); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + it('should be created', (): void => { + expect(apiService).toBeTruthy(); + }); + + it('can test HttpClient.get', (): void => { + + apiService.get(SAMPLE_URL).subscribe((res: Data) => { + expect(res).toEqual(testData); + }); + + const req = httpTestingController.expectOne(SAMPLE_URL) + expect(req.request.method).toEqual('GET'); + req.flush(new HttpResponseMock(testData)); + httpTestingController.verify(); + }); + + it('doesn\'t do anything if 401 is received', (): void => { + + apiService.get(URL_401).subscribe((res: Data) => { + expect(false); + }, (error) => {expect(error.status).toBe(401)}); + + const req = httpTestingController.expectOne(URL_401) + expect(req.request.method).toEqual('GET'); + req.flush(null, {status: 401, statusText: 'unauthenticated'}); + httpTestingController.verify(); + }); + +}); \ No newline at end of file