在这一点上我不知所措。我在试着测试一个拦截器:
测试:
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请求的响应,但它没有。
如果我删除了间谍,错误就会消失,但在这种情况下,我不会截断来自服务的响应。
jasmine 3.1.0 angular 7
发布于 2019-01-22 23:00:47
所以我有两件事要做。因为我试图返回数据,而不是发送实际的HTTP请求,所以我不应该告诉httpMock等待请求。我应该告诉你的httpMock.expectNone(testUrl)。其次,我与间谍一起发送的mockResponse并不是订阅所期望的实际HttpResponse,我只是发送了一个对象。所以我需要做一个:
new HttpResponse({ body: employee.data.employee, status: 200 });和间谍一起送回去。
希望这能节省别人几个小时的工作时间:)
https://stackoverflow.com/questions/54300359
复制相似问题