我正在尝试在 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");
}
});
});