diff --git a/quartz-manager-frontend/src/app/services/api.service.spec.ts b/quartz-manager-frontend/src/app/services/api.service.spec.ts index b3ce83f..a67abde 100644 --- a/quartz-manager-frontend/src/app/services/api.service.spec.ts +++ b/quartz-manager-frontend/src/app/services/api.service.spec.ts @@ -2,6 +2,8 @@ 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'; +import { Router} from '@angular/router'; +import {jest} from '@jest/globals' class Data{ name: string @@ -22,6 +24,8 @@ class HttpResponseMock { ) {} } +const routerSpy = jest.spyOn(Router.prototype, 'navigateByUrl'); + describe('ApiServiceTest', () => { let apiService: ApiService; @@ -36,7 +40,7 @@ describe('ApiServiceTest', () => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], - providers: [ApiService] + providers: [ApiService, {provide: Router, useValue: routerSpy}] }); apiService = TestBed.inject(ApiService); @@ -64,7 +68,11 @@ describe('ApiServiceTest', () => { apiService.get(URL_401).subscribe((res: Data) => { expect(false); - }, (error) => {expect(error.status).toBe(401)}); + }, (error) => + { + expect(error.status).toBe(401); + expect(routerSpy).toHaveBeenCalledTimes(1); + }); const req = httpTestingController.expectOne(URL_401) expect(req.request.method).toEqual('GET'); diff --git a/quartz-manager-frontend/src/app/services/api.service.ts b/quartz-manager-frontend/src/app/services/api.service.ts index d4feb83..d89a780 100644 --- a/quartz-manager-frontend/src/app/services/api.service.ts +++ b/quartz-manager-frontend/src/app/services/api.service.ts @@ -1,4 +1,5 @@ import { HttpClient, HttpHeaders, HttpResponse, HttpRequest, HttpEventType, HttpParams } from '@angular/common/http'; +import { Router} from '@angular/router'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { catchError, map, filter, tap } from 'rxjs/operators' @@ -35,7 +36,7 @@ export class ApiService { private jwtToken: string; - constructor( private http: HttpClient) { } + constructor( private http: HttpClient, private router: Router) { } setToken(token: string) { this.jwtToken = token; @@ -98,7 +99,7 @@ export class ApiService { // Display error if logged in, otherwise redirect to IDP private checkError(error: any): any { if (error && error.status === 401) { - // this.redirectIfUnauth(error); + this.router.navigate(['/login']); } else { // this.displayError(error); }