gpt4 book ai didi

Angular 单元测试 - 在 HttpInterceptor 中测试 retryWhen

转载 作者:行者123 更新时间:2023-12-04 15:38:23 29 4
gpt4 key购买 nike

我正在尝试在 http 拦截器中测试 retryWhen 运算符,但在尝试多次重复我的服务调用时出现错误:

“错误:需要一个匹配条件的请求”匹配 URL:http://someurl/tesdata “,没有找到。”

所以我有两个问题。首先,我是否打算以正确的方式进行测试,其次,为什么我不能在没有匹配错误的情况下发出多个服务请求?

我的拦截器工作正常并且正在使用 rxjs retryWhen 运算符例如:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
retryWhen(errors => errors
.pipe(
concatMap((err:HttpErrorResponse, count) => iif(
() => (count < 3),
of(err).pipe(
delay((2 + Math.random()) ** count * 200)),
throwError(err)
))
))
);
}
}

我的测试服务:

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class InterceptorTestService {

constructor(private httpClient: HttpClient) { }

getSomeData() : Observable<boolean>{
return this.httpClient
.get('http://someurl/tesdata').pipe(
map(()=>{
return true;
})
)
}
}

我的规范:


import { InterceptorTestService } from './interceptor-test.service';
import { HttpClientTestingModule, HttpTestingController, TestRequest } from '@angular/common/http/testing';

describe('InterceptorTestService', () => {

let service: InterceptorTestService;
let backend: HttpTestingController;


beforeEach(() => TestBed.configureTestingModule({
providers: [InterceptorTestService],
imports: [HttpClientTestingModule]
}));

beforeEach(() =>{
service = TestBed.get(InterceptorTestService),
backend = TestBed.get(HttpTestingController)
});

it('should be created', () => {
service.getSomeData().subscribe();


const retryCount = 3;
for (var i = 0, c = retryCount + 1; i < c; i++) {
let req = backend.expectOne('http://someurl/tesdata');
req.flush("ok");
}
});
});

最佳答案

我只是遇到了完全相同的问题,在阅读了这个 SO 答案并根据我的需要对其进行了调整后已经解决了:

Angular 7 testing retryWhen with mock http requests fails to actually retry

正在添加的关键部分:

  1. 每次刷新后打勾(2500)
  2. 进行测试 fakeAsync(以便您可以使用 tick)。

这就是我的测试现在的样子,以供引用,以防万一它可以帮助您到达目的地(很抱歉没有根据您的需要对其进行完美调整):

it("addLicensedApplication() should return an error command result if an error occurs", fakeAsync(() => {
let errResponse: any;
const mockErrorResponse = { status: 400, statusText: "Bad Request" };

service
.addLicensedApplication(aCompanyId, LicensedApplicationFlag.workshopPro)
.subscribe(res => res, err => errResponse = err);

const retryCount = 5;
for (let i = 0, c = retryCount + 1; i < c; i += 1) {
const req = httpMock
.expectOne(`${env.apiProtocol}${env.apiUrl}${Constants.addLicensedApplicationUrl}`);

req.flush(CommandResultErrorFixture, mockErrorResponse);
tick(2500);
}

expect(errResponse.error).toBe(CommandResultErrorFixture);
}));

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

关于Angular 单元测试 - 在 HttpInterceptor 中测试 retryWhen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58972065/

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