如何对Angular HttpClient 204响应进行单元测试?

时间:2018-02-06 16:46:06

标签: angular httpclient http-response-codes no-data http-status-code-204

对于无数据方案,我们的REST服务返回204。但我无法弄清楚如何测试这种情况。

it('can handle no data', (done) => {
  const testData = service.getDummyData();
  service.dataChanged$.subscribe(
    (data: Data[]) => {
      expect(data).toBeUndefined();
      done();
    }
  );
  service.getData();
  const request: TestRequest = backend.expectOne(MyService.URL);
  request.flush(undefined, { status: 204, statusText: 'No Data' });
});

我试过传递:

  • 未定义且错误
    • Error: Automatic conversion to JSON is not supported for response type.
    • 响应数据是字符串“null”

那么,我应该将什么传递给flush函数来发送空响应?我测试了服务中的响应(简化):

this.http.get<Data[]>(MyService.URL)
  .first().subscribe(
    (data: Data[]) => {
      if (data) {
        this.dataChanged$.next(data);
      } else {
        Logger.error(MyService.name, 'getData', 'No data.');
        this.dataChanged$.next(undefined);
      }
    },
    (error: Error) => {
        Logger.error(MyService.name, 'getData', error.message);
      this.dataChanged$.next(undefined);
    }
  );

1 个答案:

答案 0 :(得分:1)

所以,简单的答案是,将''传递给flush():

request.flush('', { status: 204, statusText: 'No Data' });