【发布时间】:2019-12-26 21:32:48
【问题描述】:
目标
使用nock,我正在寻找一种解决方案来模拟通过 POST multipart/form-data 上传的微小 PNG 文件。
curl:Box API 上传 PNG 文件
以下curl 脚本介绍了如何在根目录'0'中upload a file through Box API,文件名:'dummy.png'。
curl 'https://upload.box.com/api/2.0/files/content' \
--request POST \
--verbose \
--silent \
--header 'authorization: Bearer [** Access Token **]' \
--header 'Content-Type: multipart/form-data' \
--form attributes='{ "name": "dummy.png", "parent": { "id": "0" } }' \
--form file=@'./files/dummy.png'
简明回复:
Success [HTTP status: 201]
{
"total_count": 1,
"entries": [
{
"type": "file",
"name": "dummy.png",
"id": "584886508967"
}
]
}
nock 尝试:Box API 上传 PNG 文件
下一个代码 sn-p 正在使用 npm nock 工作,但是,这个模拟是不完整的:
const accessToken = v4();
const randomFileId = v4();
let boundary = '';
const scope = nock('https://upload.box.com/api/2.0/')
.log((m, d) => logger.debug(m, d))
.matchHeader('authorization', `Bearer ${accessToken}`);
scope
.matchHeader('content-type', val => {
const matches = val.match(/^multipart\/form-data; boundary=([a-zA-Z0-9\-]+)$/);
if (matches && matches.length > 1) {
boundary = matches[1];
}
return !!matches;
})
.post('/files/content', body => {
return true;
})
.reply(201, {
entries: [
{
id: randomFileId,
name: 'dummy.png',
type: 'file'
}
]
});
nock 尝试:缺少表单属性和文件二进制文件
我不清楚如何在nock 代码中包含 curl POST 请求中包含的内容:
--header 'Content-Type: multipart/form-data' \
--form attributes='{ "name": "dummy.png", "parent": { "id": "0" } }' \
--form file=@'./files/dummy.png'
我想包含在 nock POST 请求中:
-
文件 dummy.png 二进制文件 在
--form file=@'./files/dummy.png'中定义 -
文件上传元数据 由
--form attributes='{ "name": "dummy.png", "parent": { "id": "0" } }'定义
谢谢,感谢您的帮助。
【问题讨论】:
标签: multipartform-data box-api nock