首页 > 解决方案 > 使用 s3 和 multer 上传单元测试文件

问题描述

我有一个带有此路由POST api/questions/media的Express应用程序,它从客户端 req获取FormData文件(在我的情况下这是一个图像)并将它们保存到AWS S3中。在将图像存储到S3之前,我使用multerS3Transformsharp转换图像。如何编写一些测试来模拟multerS3TransforS3

import aws from 'aws-sdk'
import multer from 'multer'
import multerS3Transform from 'multer-s3-transform'
import sharp from 'sharp'
 
router.post(
    'api/questions/media',
    () => {
        uploadsQuestionImgs(req, res, error => {
            if (error) {
                return res.status(400).json({
                    message: `Invalid request. ${error}`,
                })
            } else {
                // If File not found
                if (req.files === undefined) {
                    logger.error('Error: No File Selected!')
                    return res.status(406).json('Error: No File Selected')
                } else {
                    // If Success
                    // do something wit req.files
                }
            }
        })
    }
)

const uploadsQuestionImgs = multer({
    storage: multerS3Transform({
        s3: s3,
        bucket: accessBucket,
        acl: 'public-read',
        shouldTransform: (req, file, cb) => {
            // now its transforms img all the time
            cb(null, true)
        },
        transforms: [
            {
                id: 'img',
                key: (req, file, cb) => {
                    const pathName = parseMetaData(file.originalname, req.user)
                    cb(null, pathName)
                },
                transform: (req, file, cb) => {
                    cb(
                        null,
                        sharp()
                            .resize(800, 600)
                            .jpeg()
                    )
                },
            },
        ],
        key: function(req, file, cb) {
            const pathName = parseMetaData(file.originalname, req.user)
            cb(
                null,
                path.basename(pathName, path.extname(pathName)) +
                    '-' +
                    Date.now() +
                    path.extname(pathName)
            )
        },
    }),
    limits: { fileSize: 2000000 }, // In bytes: 2000000 bytes = 2 MB
    fileFilter: function(req, file, cb) {
        checkFileType(file, cb)
    },
}).array('files', 50)

标签: javascriptexpresstestingamazon-s3multer

解决方案


推荐阅读