如何通过超级测试发送formData对象?

时间:2018-09-17 02:09:38

标签: node.js supertest superagent

我刚刚开始学习用超级测试和摩卡测试。我已经阅读了supertest的api文档,它说supertest支持superagent提供的所有较低级别的API。 SuperAgent表示我们可以通过以下方式发送formData对象:

request.post('/user')
    .send(new FormData(document.getElementById('myForm')))
    .then(callback)

但是当我尝试使用这种形式的超级测试发送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对象?我做错了什么或怎么做?如果没有,为什么?我搜索了许多相关问题,但没有一个可以解决我的问题。我现在真的很挣扎。

1 个答案:

答案 0 :(得分:0)

您可以使用.attach()的{​​{1}}方法将文件发送到服务器。 supertest的功能签名:

.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);
  });
});
相关问题