单元测试角度HttpInterceptor重试

时间:2019-01-07 12:41:44

标签: angular unit-testing

这是我尝试进行单元测试以进行角度测试的第一个项目,因此我只是弄清楚了它是如何工作的。该项目的角度为7,如果HTTP请求失败,我可以通过HttpInteceptorService重试2次:

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
    constructor() { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
        return next.handle(request).pipe(retry(2));
    }
}

到目前为止,我对此拦截器的测试:

describe('HttpInterceptorService', () => {
    beforeEach(() => TestBed.configureTestingModule({
        imports: [
            HttpClientTestingModule
        ],
        providers: [
            HttpInterceptorService,
            {
                provide: HTTP_INTERCEPTORS,
                useClass: HttpInterceptorService,
                multi: true
            }
        ]
    }));

    it('should be created', () => {
        const service: HttpInterceptorService = TestBed.get(HttpInterceptorService);
        expect(service).toBeTruthy();
    });

    it('should get http 404', () => {
        const http: HttpClient = TestBed.get(HttpClient);

        http.get('/fake-route').subscribe((response: any) => {
            expect(response).toBeTruthy();
            expect(response.status).toEqual('404');
        });
    });
});

所以我正在测试是否成功获得404,但是我不知道如何测试拦截器是否重复了两次。

修改

从某种意义上说,我错了,甚至我的'should get http 404'测试也不正常,只是总是给出错误的肯定。

编辑2

我相信我已经越来越近了,404现在可以正常工作,并且我已经为“重试”添加了一个测试,但是它仍然没有按预期工作,我认为拦截器甚至可能没有被调用... < / p>

it('should repeat failed request 2 more times', () => {
    const emsg = 'deliberate 404 error';

    jasmine.clock().install();
    spyOn(httpClient, 'get').and.callThrough();

    expect(httpClient.get).not.toHaveBeenCalled();

    httpClient.get(fakeUrl).subscribe(
    (response) => {
      fail('should have failed with the 404 error');
    },
    (error) => {
      expect(error.status).toEqual(404, 'status');
      expect(error.error).toEqual(emsg, 'message');
    });

    jasmine.clock().tick(3000);

    expect(httpClient.get).toHaveBeenCalledTimes(3);

    jasmine.clock().uninstall();
});

此测试失败,并显示“预期的间谍被叫过3次。被叫过1次”

1 个答案:

答案 0 :(得分:1)

好的,终于弄明白了,我最新的方法(第2版)也不是正确的方法。这是我重复的最终测试和工作测试:

it('should handle 404 with retry (2 times)', () => {
    const emsg = 'deliberate 404 error';

    httpClient.get(fakeUrl).subscribe(
    (response) => {
        fail('should have failed with the 404 error');
    },
    (error: HttpErrorResponse) => {
        expect(error.status).toEqual(404, 'status');
        expect(error.error).toEqual(emsg, 'message');
    });

    const retry = 2;
    for (let i = 0, c = retry + 1; i < c; i++) {
        const req = httpTestingController.expectOne(fakeUrl);
        req.flush(emsg, { status: 404, statusText: 'Not Found' });
    }
});

还添加了一个断言,可在每次测试后运行,以确保不再有未决请求:

afterEach(() => {
    httpTestingController.verify();
});