【问题标题】:Error: Expected one matching request for criteria "Match URL: xyz", found none错误:应为条件“匹配 URL:xyz”提供一个匹配请求,但未找到
【发布时间】: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。我不确定这是否是测试拦截器的正确方法,尽管大多数教程都是这样做的。感谢您的帮助。

标签: jasmine angular7


【解决方案1】:

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

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

与间谍一起返回。

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

【讨论】:

  • 这也引起了我的注意,我在自己的测试中调用了expectOne
猜你喜欢
  • 2020-06-21
  • 2019-01-08
  • 2018-11-18
  • 1970-01-01
  • 2023-03-22
  • 2021-02-20
  • 1970-01-01
  • 2021-05-13
  • 2018-12-07
相关资源
最近更新 更多