[英]Angular unit test - testing retryWhen in HttpInterceptor
我正在嘗試在 http 攔截器中測試 retryWhen 運算符,但是在嘗試多次重復我的服務調用時出現錯誤:
“錯誤:預期有一個對標准“匹配 URL: http://someurl/tesdata ”的匹配請求,但沒有找到。”
所以我有2個問題。 首先,我是否要以正確的方式進行測試,其次,為什么我不能在沒有匹配錯誤的情況下發出多個服務請求?
我的攔截器工作正常,正在使用 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 無法實際重試
正在添加的關鍵部分:
這就是我的測試現在看起來以供參考的方式,以防萬一它可以幫助你到達你要去的地方(很抱歉沒有完全適應你的需要):
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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.