Как протестировать класс с помощью функции загрузки файлов? - PullRequest
0 голосов
/ 08 марта 2019

Здравствуйте, я пытаюсь протестировать класс, который использует multer для загрузки файлов изображений в моем случае, в основном у меня есть конечная точка:

const uploadsPath = path.join(__dirname, nconf.get('UPLOADS_PATH'));

const fileuploadmanager = new FileUploadManager(uploadsPath);

router.post('/group', (req, res) => {
  fileuploadmanager.uploadFile(req, res);
});

И мой FileUploadManager класс:

import fs from 'fs';
import path from 'path';
import multer from 'multer';
import HttpStatus from 'http-status';

class FileUploadManager {
  constructor(uploadsPath) {
    this.properties = {
      uploadsPath,
      groupUploadsAbsolutePath: '',
      groupFileName: '',
      uploadedFileShortPath: '',
      uploadedFileAbsolutePath: '',
      storage: null,
      actionSuccess: {
        type: '',
        success: false,
      },
    };
  }

  checkFileType(file, cb) {
    const fileTypes = /jpeg|jpg|png/;
    const extensionName = fileTypes.test(path.extname(file.originalname).toLowerCase());
    const mimeType = fileTypes.test(file.mimetype);
    if (mimeType && extensionName) {
      const response = {
        type: 'format-supported',
        success: true,
      };
      this.properties.actionSuccess = response;
      return cb(null, true);
    }
    const response = {
      type: 'format-not-supported',
      success: false,
    };
    this.properties.actionSuccess = response;
    return response;
  }

  uploadFile(req, res) {
    let response = {};
    const groupId = req.headers.groupid;
    this.createFolder(groupId);
    if (this.actionSuccess.success) {
      const storage = multer.diskStorage({
        destination: this.groupUploadsAbsolutePath,
        filename: (req, file, cb) => {
          const imageFile = `group_${Date.now()}${path.extname(file.originalname)}`;
          this.properties.groupFileName = imageFile;
          this.properties.uploadedFileShortPath = `group_${groupId}/${imageFile}`;
          this.properties.uploadedFileAbsolutePath = `${this.groupUploadsAbsolutePath}/${imageFile}`;
          cb(null, this.groupFileName);
        },
      });

      const upload = multer({
        storage,
        limits: {
          fileSize: 1000000,
        },
        fileFilter: (req, file, cb) => {
          this.checkFileType(file, cb);
        },
      }).single('groupImage');

      upload(req, res, (err) => {
        if (err) {
          response = {
            type: 'upload-error',
            success: false,
          };
          this.properties.actionSuccess = response;
          return res.sendStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        response = {
          type: 'upload-successfully',
          success: true,
        };
        this.properties.actionSuccess = response;
        return res.status(HttpStatus.CREATED).send(this.uploadedFileShortPath);
      });
    }
  }

Итак, я пытаюсь протестировать функцию uploadFile, используя supertest следующим образом:

  describe('Test uploading file.', () => {
    it('should return a response 201, for a file uploaded', (done) => {
      request(app)
        .post('/api/v1/group')
        .attach('file', `${uploadsPath}/sample.png`)
        .end((err, res) => {
          assert.equal(res.status, 201);
          done();
        });
    }).timeout(3000);
  });

Но всегда получаю 500 server error ответ, я думаю, что это потому, что яиспользуя эту функцию как часть моего класса, у меня есть сомнения, как я могу проверить это?

...