如何用超级测验模拟multer?

问题描述 投票:5回答:1

我正在编写文件上传API,并且在模拟multer时遇到了一些麻烦。我正在尝试用supertest测试我的端点。

it('load image', async () => {
    await app
        .post(`${apiImage}`)
        .set('Authorization', 'abc123')
        .attach('avatar', `${__dirname}/test.jpg`);
        .expect(200);
});

上传效果正常。但是每次我运行测试时,都会创建新文件。因此,如何模拟multer并且不会每次都创建新文件?

node.js multer supertest
1个回答
0
投票

我有一个中间件助手来像这样包裹multer

// middleware/index.js

const multer = require('multer');
exports.multerUpload = () => multer({...});

然后像这样在我的路线中使用它

// routes.js

const { multerUpload } = require('path/to/middlewares');

app.post('/upload', multerUpload().any());

然后,在我的测试中,我可以将multerUpload存根

// test.js

const middlewares = require('path/to/middlewares');
sinon.stub(middlewares, 'multerUpload').callsFake(
      () => {
        return {
          any() {
            return (req, res, next) => {
              // You can do whatever you like to the request body here e.g
              req.body = { title: req.query.title };
              req.files = [{ location: 'sample.url', key: 'sample.key' }];
              return next();
            };
          },
        };
      },
);
© www.soinside.com 2019 - 2024. All rights reserved.