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.