我正在使用HttpClient POST将文件上传到我的后端服务器。文件上传正常。但是,我无法为此服务编写单元测试。使用HttpClientTestingModule
和HttpTestingController
。下面是我的代码
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>"
}
不确定我在这里想念什么。文件上传功能按预期工作,唯一的问题是单元测试。
答案 0 :(得分:0)
结果是我们无法在控制台中检查FormData
,这就是我得到空对象的原因。多亏this SO Answer,我才能够从请求主体(即FormData)中获取文件对象。我要做的就是
mock.request.body.get('data') // --> This will give me the file object posted in the request