Search code examples
javascriptnode.jsjestjsts-jest

Test multiple file upload with jest nodejs


I am building an application with NodeJs where multiple files will be uploaded. Below is my test case and I am getting this error Argument of type 'string[]' is not assignable to parameter of type 'MultipartValueSingle'.

This is the test case

it('Create feed (POST)', () => {
        const video = path.resolve(__dirname, `../test-files/movie_video.mp4`);
        const image = path.resolve(__dirname, `../test-files/thumbnail.jpg`);
        const pdfDoc = path.resolve(__dirname, `../test-files/pdf_doc.pdf`);

        const multipleFiles : string[] = [video, image, pdfDoc]

        return request(app.getHttpServer())
            .post('/feed')
            .set('content-type', 'application/octet-stream')
            .set('Authorization', 'Bearer ' + accessToken)
            .field('text', 'Aenean imperdiet. Nam ipsum risus,. Curabitur suscipit suscipit tellus.')
            .field('payment_amount', 0)
            .attach('postDocs', multipleFiles)
            .expect(function (res) {
                if (!('message' in res.body) || !('payload' in res.body)) {
                    throw new Error('Response should contain message and payload.');
                } else if (res.body.message !== StatusMessages.Default) {
                    throw new Error('User not logged in');
                }
                if (!('user' in res.body.payload)) {
                    throw new Error('Payload should contain user.');
                }
                adminAccessToken = res.body.payload.access_token;
            });
    });

Solution

  • The error message is obvious, you should attach the multiple files by calling .attach() multiple times.

    E.g.

    index.ts:

    import express from 'express';
    import multer from 'multer';
    
    const app = express();
    
    const upload = multer();
    const cpUpload = upload.fields([{ name: 'video' }, { name: 'image' }, { name: 'pdfDoc' }]);
    app.post('/feed', cpUpload, (req, res) => {
      console.log(req.files);
      console.log(req.body);
      res.sendStatus(200);
    });
    
    export { app };
    

    index.test.ts:

    import path from 'path';
    import request from 'supertest';
    import { app } from '.';
    
    describe('69663276', () => {
      it('Create feed (POST)', () => {
        const video = path.resolve(__dirname, `./movie_video.mp4`);
        const image = path.resolve(__dirname, `./thumbnail.jpg`);
        const pdfDoc = path.resolve(__dirname, `./pdf_doc.pdf`);
    
        const accessToken = '123';
        return request(app)
          .post('/feed')
          .set('content-type', 'application/octet-stream')
          .set('Authorization', 'Bearer ' + accessToken)
          .field('text', 'Aenean imperdiet. Nam ipsum risus,. Curabitur suscipit suscipit tellus.')
          .field('payment_amount', 0)
          .attach('video', video)
          .attach('image', image)
          .attach('pdfDoc', pdfDoc)
          .expect(200);
      });
    });
    

    test result:

     PASS  examples/69663276/index.test.ts (11.544 s)
      69663276
        ✓ Create feed (POST) (71 ms)
    
      console.log
        [Object: null prototype] {
          video: [
            {
              fieldname: 'video',
              originalname: 'movie_video.mp4',
              encoding: '7bit',
              mimetype: 'video/mp4',
              buffer: <Buffer >,
              size: 0
            }
          ],
          image: [
            {
              fieldname: 'image',
              originalname: 'thumbnail.jpg',
              encoding: '7bit',
              mimetype: 'image/jpeg',
              buffer: <Buffer >,
              size: 0
            }
          ],
          pdfDoc: [
            {
              fieldname: 'pdfDoc',
              originalname: 'pdf_doc.pdf',
              encoding: '7bit',
              mimetype: 'application/pdf',
              buffer: <Buffer >,
              size: 0
            }
          ]
        }
    
          at examples/69663276/index.ts:9:11
    
      console.log
        [Object: null prototype] {
          text: 'Aenean imperdiet. Nam ipsum risus,. Curabitur suscipit suscipit tellus.',
          payment_amount: '0'
        }
    
          at examples/69663276/index.ts:10:11
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        12.795 s