我刚开始学习用supertest和mocha做测试。我读过supertest的api文档,里面说supertest支持superagent提供的所有底层API。SuperAgent说我们可以通过以下方式发送formData对象:
request.post('/user')
.send(new FormData(document.getElementById('myForm')))
.then(callback)但是当我尝试使用supertest发送一个formData对象时,如下所示:
server
.post('/goal_model/images/' + userId + '/' + tmid)
.set('Authorization',`Bearer ${token}`)
.send(formData)
.expect("Content-type",/json/)
.expect(201)
.end(function(err,res){
should(res.status).equal(201);
console.log(res.message);
done();
});其中formData类似于:
let file;
let formData = new FormData();
let fn = "../../../Downloads/Images/5k.jpg";
formData.append("image", file);然后,当我尝试发送这个对象时,它只是说:
TypeError: "string" must be a string, Buffer, or ArrayBuffer可以用这种方式发送formData对象吗?我做错了什么,或者该怎么做?若否,原因为何?我搜索了很多相关的问题,但没有一个能解决我的问题。我现在真的很纠结。
发布于 2020-03-30 11:42:55
您可以使用supertest的.attach()方法将您的文件发送到服务器。.attach的函数签名:
attach(field: string, file: MultipartValueSingle, options?: string | { filename?: string; contentType?: string }): this;file参数的数据类型可以是:
type MultipartValueSingle = Blob | Buffer | fs.ReadStream | string | boolean | number;在这里,我将一个文件路径传递给.attach方法。
例如。
server.ts
import express from 'express';
import multer from 'multer';
import path from 'path';
const app = express();
const port = 3000;
const upload = multer({ dest: path.resolve(__dirname, 'uploads/') });
app.post('/upload', upload.single('avatar'), (req, res) => {
console.log('file:', req.file);
console.log('content-type:', req.get('Content-Type'));
res.sendStatus(200);
});
if (require.main === module) {
app.listen(port, () => {
console.log(`HTTP server is listening on http://localhost:${port}`);
});
}
export { app };server.test.ts
import { app } from './server';
import request from 'supertest';
import path from 'path';
describe('52359964', () => {
it('should pass', () => {
return request(app)
.post('/upload')
.attach('avatar', path.resolve(__dirname, './downloads/5k.jpg'))
.expect(200);
});
});集成测试结果:
52359964
file: { fieldname: 'avatar',
originalname: '5k.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination:
'/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/52359964/uploads',
filename: '329756ab22bf7abe2d27866a322c2f30',
path:
'/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/52359964/uploads/329756ab22bf7abe2d27866a322c2f30',
size: 0 }
content-type: multipart/form-data; boundary=--------------------------777489367435889931561092
✓ should pass (42ms)
1 passing (48ms)https://stackoverflow.com/questions/52359964
复制相似问题