使用Jest测试时,Express应用程序中未定义Multer

7rtdyuoh  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(64)

我使用jest来测试我的快递应用程序与TS使用multer上传文件.但我的测试结束与错误"TypeError: Cannot read properties of undefined (reading 'diskStorage')".该应用程序工作正常,错误是只有当我测试.
我的错误发生在-

import multer from "multer";

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "images/");
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
        cb(
            null,
            (
                file.fieldname +
                "-" +
                uniqueSuffix +
                "-" +
                file.originalname
            ).replace(/ /g, "_")
        );
    },
});

function filter(req: object, file: Express.Multer.File, cb: Function) {
    cb(null, file.mimetype === "image/jpg" || file.mimetype === "image/jpeg");
}

const postStorage = multer({
    storage: storage,
    fileFilter: filter,
    limits: {
        fileSize: 1024 * 1024, // max size in bytes
    },
});

export default postStorage;

字符串
我把它用在我的路线上-

const router = express.Router();

router.get("/", getAll);
router.post(
    "/",
    postStorage.fields([
        { name: "main_image", maxCount: 1 },
        { name: "additional_images", maxCount: 5 },
    ]),
    RequestValidator(PostSchema, "body"),
    insert
);

export default router;


我的笑话代码是-

describe("do ", () => {
    describe("dodo", () => {
        it("dododo", async () => {
            await supertest(app).get("/").expect(200);
            return true;
        });
    });
});


我真的很感激你的帮助谢谢。

vfhzx4xs

vfhzx4xs1#

你在这里做的基本上是集成测试,这意味着你实际上发出了请求,并实际上将数据存储在db中,对吗?

万一我是对的
那么错误几乎是预料之中的

因为你实际上是在向那个端点发出请求,但并没有将数据被动地发送到那个端点或图像URL,如果你想说的话。

万一我错了

假设你正在做单元测试,这是不可能的,那么你必须使用模拟数据来创建相同的行为。
Here's the example how to use multer for unit testing

相关问题