【问题标题】:Angular test : mock a HttpResponse containing a blob角度测试:模拟包含 blob 的 HttpResponse
【发布时间】:2020-07-23 07:53:11
【问题描述】:

我正在开发一个 Angular 9 应用程序,我正在编写单元测试,这要感谢 jest。我的 Angular 服务调用一个 Spring API,它返回一个 CSV 文件以供下载。我想进行单元测试,但我无法模拟 HttpResponse。

* MyService.ts *

downloadCsv(id: string) {
    return this.http.get('/api/ + id + `/csv/`,
      { responseType: 'blob' as 'json', observe: 'response' });
  }

* MyService.spec.ts *

  it(`should call the GET API and return a csv file as result`, () => {
    // GIVEN 
    const expectedData: Blob = new Blob(['a', 'b', 'c', 'd']);

    // WHEN
    let actualData = {};
    service.downloadCsv('1').subscribe(data => {
      actualData = data;
    });

    // THEN
    backendMock.expectOne((req: HttpRequest<any>) => {
      return req.url === `/api/` + '1' + `/csv/`
        && req.method === 'GET';
    },  `GET data to ${'/api/'}`)
      .flush(expectedData);

    expect(actualData).toEqual(expectedData);
  });

我不知道如何构建一个包含 blob 的 HttpResponse,即使我试图在 expectedData 中放置一个新的 HttpResponse(我没有找到太多的例子,文档也没有真正帮助我:/( HttpResponse documentation))

我正在等待的响应如下所示:

有人可以帮我吗?

【问题讨论】:

    标签: angular unit-testing jestjs blob httpresponse


    【解决方案1】:

    你可以做这样的事情来模拟响应

    const fakeFile = (): File => {
    const blob = new Blob([''], { type: 'text/html' });
    return blob as File;
    };
    

    希望这会有所帮助:)

    【讨论】:

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