gpt4 book ai didi

angular - 如何使用 Jasmine 在 Angular 中对 HTTP 拦截器进行单元测试

转载 作者:行者123 更新时间:2023-12-05 00:52:51 24 4
gpt4 key购买 nike

我的 Angular 应用程序中有以下 http 拦截器,我想使用 Jasmine 对其进行单元测试。我用谷歌搜索了其中一些并尝试了,但它没有按预期工作。请在下面找到 HttpInterceptorService.ts 文件代码

export class HttpInterceptorService Implements HttpInterceptor {
counter = 0;
constructor(private loaderService: LoaderService) { }
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (req.url !== '/getUsers') {
this.counter ++;
}
this.loaderService.setStatus(true);
return next.handle(req).pipe(
finalize(() => {
if (req.url !== 'getUsers') {
this.counter --;
}
if (this.counter === 0) {
this.loaderService.setStatus(false);
}
};
);
}
}

以下是我目前尝试的 HttpInterceptor.service.spec.ts 文件代码。我不确定如何测试其中的特定方法。

describe('HttpInterceptorService', () => {
let httpService: HttpService;
let httpMock: HttpTestingController;
let interceptor: HttpInterceptorService;

beforeEach(()=> {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
HttpService,
{provide:HTTP_INTERCEPTOR, useClass: HttpInterceptorService, multi: true},
]
});
httpService = TestBed.get(HttpService);
httpMock = TestBed.get(HttpTestingController);
interceptor = TestBed.get(HttpInterceptorService);
});

it('should increment the counter for all api's expect getUsers', ()=> {
httpService.get('getAdminList').subscribe(res => {
expect(res).toBeTruthy();
expect(interceptor.counter).toBeGreaterThan(0);
});
});


});

在检查引用代码后,我可以通过上述更改覆盖几行代码。但我仍然无法涵盖 finalize 方法。请求帮助。

最佳答案

下面的代码有助于覆盖 finalize 运算符中的代码。

const next: any = {
handle: () => {
return Observable.create(subscriber => {
subscriber.complete();
});
}
};

const requestMock = new HttpRequest('GET', '/test');

interceptor.intercept(requestMock, next).subscribe(() => {
expect(interceptor.counter).toBeGreaterThan(0);
});

关于angular - 如何使用 Jasmine 在 Angular 中对 HTTP 拦截器进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69100788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com