Angular Testing : mock a HttpResponse containing a blob

标签 angular unit-testing jestjs blob httpresponse

我正在开发一个 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 ))

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

HttpResponse I have to mock

有人能帮我吗 ?

最佳答案

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

const fakeFile = (): File => {
const blob = new Blob([''], { type: 'text/html' });
return blob as File;
};
希望这可以帮助 :)

关于 Angular Testing : mock a HttpResponse containing a blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61142428/

相关文章:

html - 动态设置ionic2组件的Style属性

c# - 我如何断言/验证受最小起订量保护的方法?

javascript - 使用 React.memo 时 Jest Snapshot 错误

node.js - 使用外部 babel 配置会破坏 Node/React 应用程序 - 内部服务器错误

angular - 具有外观轮廓的 mat-form-field 效果不佳

javascript - 如何从 TypeScript 项目中调用 JavaScript 库?

unit-testing - MVCContrib 带区域的测试路线

unit-testing - 正面、负面或不明确的单元测试消息?

reactjs - 如何测试使用自定义 TypeScript React Hook 的组件?

html - 如何在 anchor 链接上单击 Angular 打开 Bootstrap 弹出模式