首页 > 解决方案 > 使用 HttpClient 在 Angular 中测试文件上传并且不能期望 FormData

问题描述

我正在使用 HttpClient POST 将文件上传到我的后端服务器。文件上传工作正常。但是,我无法为我的服务编写单元测试。使用HttpClientTestingModuleHttpTestingController。下面是我的代码

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.

我的服务(上传文件的服务)如下

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));

当我将模拟请求对象记录到控制台时,我得到以下信息

{
   "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>"
}

不知道我在这里错过了什么。文件上传功能按预期工作,唯一的问题是单元测试。

标签: angularjasmine

解决方案


事实证明,我们无法FormData在控制台中进行检查,这就是我得到一个空对象的原因。多亏了这个 SO Answer,我才能够从请求正文(即 FormData)中获取文件对象。我所要做的就是

mock.request.body.get('data') // --> This will give me the file object posted in the request

推荐阅读