嗨,我正在尝试测试一个使用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
的响应,我认为这是因为我在班级中使用了该函数,我怀疑如何测试它?