【发布时间】:2019-01-22 23:00:47
【问题描述】:
我在这一点上不知所措。我正在尝试测试拦截器:
测试:
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
【问题讨论】:
-
我没有看到对您的拦截器代码的调用?也许 HttpTestingController 正在阻止它拦截 apiService 调用...
-
@dmcgrandle - 拦截器中的控制台日志确实运行,并且记录的 req.url 是
expectOne调用中的 url。我不确定这是否是测试拦截器的正确方法,尽管大多数教程都是这样做的。感谢您的帮助。