Error: Expected one matching request for criteria "Match URL: xyz", found none

Error: Expected one matching request for criteria "Match URL: xyz", found none

此时我不知所措。我正在尝试测试拦截器:

测试:

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 angular7

所以我在这里发生了两件事。因为我试图 return 数据而不是发送实际的 HTTP 请求,所以我不应该告诉 httpMock 期待一个请求。我应该告诉它 httpMock.expectNone(testUrl)。其次,我用间谍发送的 mockResponse 并不是订阅期望的实际 HttpResponse,我只是发送了一个对象。所以我需要做一个:

new HttpResponse({ body: employee.data.employee, status: 200 });

和间谍一起送回去。

希望这可以节省其他人的工作时间:)