簡體   English   中英

如何對 Angular Interceptor 進行單元測試

[英]How to unit test Angular Interceptor

我一直在尋找測試 Angular Interceptor 代碼以進行錯誤處理的方法,但我似乎無法弄清楚如何。

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService, private router: Router) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError(err => {

            let errorMessage = '';
            if(err instanceof HttpErrorResponse) { // server side error
                                
                switch (err.status) {
                    case 401:  
                        // auto logout if 401 response returned from api                          
                        errorMessage = "Ongeldige inloggegevens"  
                        break;          
                    case 500:     //server error
                        errorMessage = `Error Status: ${err.status}\nMessage: ${err.message}`;
                        this.router.navigate([`/code500`]);
                        break;
            }

            return throwError(errorMessage);
        }
    }
  ))
}
}

嘗試這樣的事情,希望它有所幫助。

import { HttpErrorResponse} from '@angular/common/http';
import { ErrorInterceptor} from './ErrorInterceptor';
import { of } from 'rxjs';
import { take } from 'rxjs/operators';
import { HttpErrorResponse} from '@angular/common/http';
import { AuthenticationService} from '....';

describe('ErrorInterceptor', () => {
   let interceptor: ErrorInterceptor;
   let mockAuthenticationService: AuthenticationService;
    beforeEach(() => {
            mockAuthenticationService = {
                logout: jasmine.createSpy('logout')
            };
            mockRouter = {
                navigate: jasmine.createSpy('navigate')
            };
       interceptor = new ErrorInterceptor(mockAuthenticationService as any, mockRouter as any);
    });


    describe('intercept', () => {
        beforeEach(() => {
            const payload = {
                    statue: 401
                },
                response = new HttpErrorResponse(payload),
                next: any = {
                    handle: jasmine.createSpy('handle').and.callFake(() => of(response))
                };

            interceptor.intercept(response as any, next).pipe(take(1))
              .subscribe();
        });


    describe('when status is 401', () => {
        it('should logout',() => {                 

       expect(mockAuthenticationService.logout).toHaveBeenCalled();
       expect(mockRouter.navigate).toHaveBeenCalledWith([`\logout`]);
        });

    });
   ...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM