我正在编写文件上传API,并且在模拟multer时遇到了一些麻烦。我试图用超级试验来测试我的终端。
it('load image', async () => {
await app
.post(`${apiImage}`)
.set('Authorization', 'abc123')
.attach('avatar', `${__dirname}/test.jpg`);
.expect(200);
});
上传按预期工作。但每次我运行测试时,都会创建新文件。那么,如何模拟multer并且不会每次都创建新文件?
答案 0 :(得分:2)
我有一个中间件助手来包裹这样的木瓜子
// 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();
};
},
};
},
);
答案 1 :(得分:0)
使用Jest模拟Multer(类似于ans,但使用Jest)
App.js
使用multer作为中间件
const app = express();
app.use()
app.use(multer({ dest: FILE_UPLOAD_PATH }).single('datafile'));
app.use('/api', apiRoutes);
apiRoute.js
router.post('/datasources', async function (req, res) {
...
});
apiRoute.test.js
const multer = require('multer');
jest.mock('multer');
multer.mockImplementation(() => {
return {
single() {
return (req, res, next) => {
req.body = { title: req.query.title };
req.file = [{ originalname: 'sample.name', mimetype: 'sample.type', path: 'sample.url' }];
return next();
};
},
};
});
.
.
.