错误:对于条件“匹配URL:xyz”,预期有一个匹配请求,但未找到

时间:2019-01-22 02:19:12

标签: jasmine angular7

我现在很茫然。我正在尝试测试拦截器:

测试:

\n
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

如果我删除间谍,则错误会消失,但在这种情况下,我不会从服务中获取响应。

茉莉3.1.0 角7

1 个答案:

答案 0 :(得分:1)

所以我在这里发生了两件事。由于我试图返回数据而不发送实际的HTTP请求,因此我不应该告诉httpMock期望该请求。我应该告诉它onReceived = async (notification) => { //App is opened! console.log("Notification received: ", notification); await this.setState({ // It will wait until finish setState. pushNotification: notification, visible: true }); if (notification.payload.notificationID != null) { firebase.analytics().logEvent("Popup_Link_Button", { notificationID: notification.payload.notificationID, clicked: true }); } }; 。其次,我与间谍发送的模拟响应不是订阅所期望的实际HttpResponse,而是发送一个对象。所以我需要做一个:

httpMock.expectNone(testUrl)

与间谍一起发回。

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