Angular test : mock a HttpResponse containing a blob
Asked Answered
M

1

6

I'm working on an Angular 9 application and I'm writing unit tests thanks to jest. My angular service calls a spring API which returns a CSV file to download. I'd like to unit test but I'm not able to mock the 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);
  });

I don't know how to build a HttpResponse containing a blob even when I'm trying to put a new HttpResponse in expectedData (I don't find really much examples and the doc doesn't really help me :/ (HttpResponse documentation))

The response I'm waiting for looks like this :

HttpResponse I have to mock

Can someone help me ?

Mangrove answered 10/4, 2020 at 14:29 Comment(0)
C
10

you can do something like this to mock the response

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

Hope this helps :)

Coffeehouse answered 18/9, 2020 at 12:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.