如何对从管道可观察到的错误进行捕获的Angular打字稿Http错误拦截器进行单元测试?

Dou*_*Jr. 6 unit-testing rxjs typescript angular

我正在运行一个实验,通过测试其他人的代码来学习角度和打字稿(例如自动化单元测试和端到端测试)。经过测试后,我计划将其重新用于我正在大学教室中进行的宠物项目。

我至少已经从此处对代码进行单元测试了一半:http : //jasonwatmore.com/post/2018/05/16/angular-6-user-registration-and-login-example-tutorial

我一直在尝试下面的代码进行单元测试,但是到目前为止,我根据自己的想法或互联网上的想法尝试过的一切都没有成功:

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { AuthenticationService } from "src/app/authenticationService/AuthenticationService";
import { Observable, throwError } from "rxjs";
import { catchError } from "rxjs/operators";
import { Injectable } from "@angular/core";

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

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

            console.log('in error handle')

            if (err.status === 401) { 
                // auto logout if 401 response returned from api
                this.authenticationService.logout();
                location.reload(true);
            }

            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }

}
Run Code Online (Sandbox Code Playgroud)

以下测试代码和多种变体未能成功显示在控制台日志中,并显示“错误句柄”消息:

import { ErrorInterceptor } from "./ErrorInterceptor";
import { of, throwError, defer } from "rxjs";

describe('ErrorInterceptor', () => {
    let errorInterceptor;
    let authenticationServiceSpy;

    beforeEach(() => {
        authenticationServiceSpy = jasmine.createSpyObj('AuthenticationService', ['logout']);
        errorInterceptor = new ErrorInterceptor(authenticationServiceSpy);
    })

    it('should create', () => {
        expect(errorInterceptor).toBeTruthy();
    })

    describe('intercept', () => {
        let httpRequestSpy;
        let httpHandlerSpy;
        const error = {status: 401, statusText: 'error'};

        it('should auto logout if 401 response returned from api', () => {
            //arrange
            httpRequestSpy = jasmine.createSpyObj('HttpRequest', ['doesNotMatter']);
            httpHandlerSpy = jasmine.createSpyObj('HttpHandler', ['handle']);
            httpHandlerSpy.handle.and.returnValue({
                pipe: () => {
                return fakeAsyncResponseWithError({});
                }
            });

            //act
            errorInterceptor.intercept(httpRequestSpy, httpHandlerSpy);

            //assert
            //TBD

            function fakeAsyncResponseWithError<T>(data: T) {
                return defer(() => throwError(error));
            }
        })
    })
})
Run Code Online (Sandbox Code Playgroud)

dmc*_*dle 6

这里有几个问题。

  • 首先,您的from的返回值httpHandlerSpy.handle()必须是Observable,因为它将已经具有管道运算符,然后HttpInterceptor代码可以根据需要将其通过管道传递给catchError。
  • 其次,HttpInterceptor返回一个Observable,要使其“执行”,需要对其进行订阅。

我整理了一个Stackblitz来演示如何解决这个问题。

在Stackblitz中,这是spec(it函数):

it('should auto logout if 401 response returned from api', () => {
    //arrange
    httpRequestSpy = jasmine.createSpyObj('HttpRequest', ['doesNotMatter']);
    httpHandlerSpy = jasmine.createSpyObj('HttpHandler', ['handle']);
    httpHandlerSpy.handle.and.returnValue(throwError(
        {error: 
            {message: 'test-error'}
        }
    ));
    //act
    errorInterceptor.intercept(httpRequestSpy, httpHandlerSpy)
        .subscribe(
            result => console.log('good', result), 
            err => { 
                console.log('error', err);
                expect(err).toEqual('test-error');
            }
        );

    //assert

})
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。