2

I am using HttpClient POST to upload a file to my backend server. The file upload is working fine. However, I am unable to write a unit test for my service for the same. Using HttpClientTestingModule and HttpTestingController. Below is my code

const file = new File([''], 'file.txt');
service.postFile(file).then();

const mock = httpTestingController.expectOne(url);
expect(mock.request.method).toEqual('POST');
expect(mock.request.body) // <-- Unable to get body from the request here.

My service (the one that uploads the file) is as below

const formData: FormData = new FormData();
formData.append('data', file);

const req = new HttpRequest('POST', url, formData, {
  headers: new HttpHeaders({'Content-Type': 'multipart/form-data'}),
  reportProgress: true
});

this.httpClient
  .request(req)
  .toPromise()
  .then()
  .catch((error: HttpErrorResponse) => console.log(error));

When I log the mock request object to console, I get the following

{
   "url":"<url>",
   "body: {}, <-- this should be the FormData
   "reportProgress": true,
   "withCredentials": false,
   "responseType": "json",
   "method": "POST",
   "headers": { "normalizedNames": {},"lazyUpdate": null },
   "params": { "updates":null, "cloneFrom": null, "encoder":{}, "map": null},
   "urlWithParams": "<url>"
}

Not sure what am I missing here. The file upload functionality works as expected, only issue is the unit test.

Ralph Willgoss
  • 11,750
  • 4
  • 64
  • 67
Taher
  • 732
  • 1
  • 9
  • 26

1 Answers1

3

Turns out that we cannot inspect FormData in console and that is the reason I was getting an empty object. Thanks to this SO Answer I was able to get the file object from request body (i.e. FormData). All I had to do was

mock.request.body.get('data') // --> This will give me the file object posted in the request
Taher
  • 732
  • 1
  • 9
  • 26
  • Thanks, exactly what I was after. I was trying to use jasmine's toEqual() method to assert some formData and it was giving me false positives. – Ralph Willgoss May 19 '21 at 11:24