#26 added redirect to login in case of 401

This commit is contained in:
fabio.formosa
2020-11-04 00:34:23 +01:00
parent 10bea2311e
commit d950ff29b2
2 changed files with 13 additions and 4 deletions

View File

@@ -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');

View File

@@ -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);
}