How to mock multer with supertest?
I had a middleware helper to wrap multer like this
// middleware/index.js
const multer = require('multer');
exports.multerUpload = () => multer({...});
Then use it in my routes like so
// routes.js
const { multerUpload } = require('path/to/middlewares');
app.post('/upload', multerUpload().any());
Then, in my tests, I can stub out 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();
};
},
};
},
);
Mock Multer using Jest (Similar to above ans but using Jest)
App.js
Used multer as middleware
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();
};
},
};
});
.
.
.