【问题标题】:HttpTestingController.expectOne() with queryparameters带有查询参数的 HttpTestingController.expectOne()
【发布时间】:2019-02-19 16:57:27
【问题描述】:

我是使用 Jasmine/Karma 进行角度测试的新手。我在使用HttpTestingController 测试角度服务时遇到了问题。这是源代码的一部分:

getProfile(userName: string) {
    let config = {
      params: {
        user_id: "test"    
      }
    }
    return this.http
      .get(`https://api.github.com/users/${userName}`, config);
  }

使用expectOne of HttpTestingController 调用服务时:

it('should add an Authorization header', () => {
let response;
userService.getProfile('blacksonic').subscribe(response => {
  expect(response).toBeTruthy();    });


const req = 
httpMock.expectOne({ method: 'GET', url:'https://api.github.com/users/blacksonic' });
                   });

我收到以下错误:

Error: Expected one matching request for criteria "Match method: GET, URL: https://api.github.com/users/blacksonic", found none.
at HttpClientTestingBackend.expectOne (./node_modules/@angular/common/fesm5/http/testing.js?:301:19)
at UserContext.eval (./src/app/Interceptors/Interceptor.spec.ts?:85:28)
at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:387:26)
at ProxyZoneSpec.onInvoke (./node_modules/zone.js/dist/zone-testing.js?:287:39)
at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:386:32)
at Zone.run (./node_modules/zone.js/dist/zone.js?:137:43)
at runInTestZone (./node_modules/zone.js/dist/zone-testing.js?:508:34)
at UserContext.eval (./node_modules/zone.js/dist/zone-testing.js?:523:20)

【问题讨论】:

    标签: angular testing karma-jasmine


    【解决方案1】:

    您正在传递一个参数。所以这样的事情会起作用:

    const req = httpMock.expectOne(
     { method: 'GET', url:'https://api.github.com/users/blacksonic?user_id=test' });
    

    【讨论】:

    • 我什至测试了这个案例,但它不起作用,同样的错误。
    • 问题通过替换解决:const req = httpMock.expectOne({ method: 'GET', url:'https://api.github.com/users/blacksonic' });; const req = httpMock.expectOne( (req: HttpRequest<any>) => req.urlWithParams == "https://api.github.com/users/blacksonic?user_id=test");
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多