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

时间:2018-12-08 15:18:20

标签: angular typescript unit-testing rxjs

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

我至少已经在这里对代码进行了单元测试了一半: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);
        }))
    }

}

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

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

1 个答案:

答案 0 :(得分:3)

这里有几个问题。

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

我整理了一个Stackblitz来演示如何实现此目的。

在Stackblitz中,这是规格(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

})

我希望这会有所帮助。