首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >错误:对于条件“匹配URL: xyz",应有一个匹配请求,但未找到

错误:对于条件“匹配URL: xyz",应有一个匹配请求,但未找到
EN

Stack Overflow用户
提问于 2019-01-22 10:19:12
回答 1查看 5.4K关注 0票数 1

在这一点上我不知所措。我在试着测试一个拦截器:

测试:

代码语言:javascript
运行
复制
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);
  }));
})
代码语言:javascript
运行
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-22 23:00:47

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

代码语言:javascript
运行
复制
new HttpResponse({ body: employee.data.employee, status: 200 });

和间谍一起送回去。

希望这能节省别人几个小时的工作时间:)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54300359

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档