Я в растерянности на данный момент. Я пытаюсь проверить перехватчик:
TEST:
const testBedBase = {
imports: [HttpClientTestingModule],
providers: [
ApiService,
CacheService,
{ provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }
]
};
describe('CacheInterceptor with cached data', () => {
let httpMock: HttpTestingController;
let apiService: ApiService;
let cacheService: CacheService;
beforeEach(() => {
TestBed.configureTestingModule(testBedBase);
httpMock = TestBed.get(HttpTestingController);
apiService = TestBed.get(ApiService);
cacheService = TestBed.get(CacheService);
});
afterEach(() => {
httpMock.verify();
});
it('should respond with cached data if available', async( () => {
const testUrl = `http://localhost:3000/api/v1/employee/123`;
spyOn(cacheService, 'get').and.returnValue(mockResponse);
apiService.getEmployee('123').subscribe(res => {
// apiService calls http://localhost:3000/api/v1/employee/123 as tested in the interceptor
expect(res).toBeTruthy();
expect(res).toBe(mockResponse);
});
const req = httpMock.expectOne(testUrl);
req.flush(mockResponse);
}));
})
intercept(req: HttpRequest<any>, next: HttpHandler) {
const cachedResponse = this.cache.get(req.url);
console.log(cachedResponse, req.url); // this returns the http://localhost:3000/api/v1/employee/123 as seen in the getEmployee request
return cachedResponse ? Observable.of(cachedResponse) : this.sendRequest(req, next);
}
Насколько я понимаю, spyOn(cacheService, 'get').and.returnValue(mockResponse);
должен установить ответ на запрос this.cache.get
в перехватчике, но это не так. И я постоянно получаю:
Failed: Expected one matching request for criteria "Match URL: http://localhost:3000/api/v1/employee/123", found none.
Если я удалю шпиона, ошибка исчезнет, но в этом случае я не заглушу ответ службы.
жасмин 3.1.0
угловой 7