Search code examples
node.jsmultersupertest

How to mock multer with supertest?


I'm writing file upload API and have some troubles with mocking multer. I'm trying to test my endpoint with supertest.

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

Upload works as expected. But every time when I run test, new file being created. So, how to mock multer and does not create new file every time?


Solution

  • 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();
                };
              },
            };
          },
    );