【问题标题】:@angular/common/http/testing TestRequest.flush a boolean value@angular/common/http/testing TestRequest.flush 一个布尔值
【发布时间】:2018-07-10 17:26:01
【问题描述】:

我想测试使用将返回 truefalse 作为响应的端点。不是'true',而是一个布尔值true。我正在使用@angular/common/http/testing 模块。对于其他响应值,我可以使用TestResponse.flush(value),但这不适用于boolean 值。相反,测试模块抱怨

响应类型不支持自动转换为 JSON。


这是我的测试代码:

const FLUSH_OK = {status: 200, statusText: 'Ok'};

//.. describe...
it('should work', async(() => {
  service.myFunction().subscribe((data) => { // my Function returns Observable<boolean>, the real endpoint returns a true/false boolean
    expect(data).toEqual(true);
  });

  // this fails: Failed: Automatic conversion to JSON is not supported for response type.
  httpMock.expectOne((req) => {
    return req.url === MY_URL;
  }).flush(true, FLUSH_OK);

 // this also fails: Expected 'true' to equal true.
 // httpMock.expectOne((req) => {
 //   return req.url === MY_URL;
 // }).flush('true', FLUSH_OK);

}));

【问题讨论】:

  • 哦,是的……嗯,就是这样。
  • 这似乎确实给出了这个错误:'Observable' 类型的参数不可分配给'Expected' 类型的参数。类型“Observable”不可分配给类型“ObjectContaining”。
  • 这被认为是测试模块中的一个错误,并于 2020-10-05 修复:见angular issue 37893

标签: angular typescript http mocking boolean


【解决方案1】:

使用event 方法而不是flush 允许您指定响应正文的类型。

const req = httpMock.expectOne('some-url');
req.event(new HttpResponse<boolean>({body: true}));

您还可以选择设置其他属性,例如statusstatusText

HttpResponse docs

Original answer

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多