angular - 使用 HttpClient 在 Angular 中测试文件上传并且不能期望 FormData
问题描述
我正在使用 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>"
}
不知道我在这里错过了什么。文件上传功能按预期工作,唯一的问题是单元测试。
解决方案
事实证明,我们无法FormData
在控制台中进行检查,这就是我得到一个空对象的原因。多亏了这个 SO Answer,我才能够从请求正文(即 FormData)中获取文件对象。我所要做的就是
mock.request.body.get('data') // --> This will give me the file object posted in the request
推荐阅读
- html - 使用@media print 使嵌入的 Soundcloud 缩略图可打印
- python - 如何使用 SqlAlchemy 修复数据绑定问题
- react-native - React Navigation TabBar 活动选项卡
- javascript - 从字符串中删除所有
标签 - 未按预期工作 - jenkins - Kubernetes POD 故障转移
- graphql - 是否可以在联合中混合标量和对象类型
- r - 字符串匹配以下载某些文件
- gekko - 我正在尝试在 PYTHON 上使用 GEKKO 来控制 cstr。CVS 是罐的温度和液位
- java - 加天时的不同日期
- bash - bash 可以生成多个进程并报告成功运行的进程数吗?