我正在使用JEST测试我用TS制作的Express应用程序,它使用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;

我的jest密码是-

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

如果能有任何帮助,我将不胜感激.谢谢.

推荐答案

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

In Case i'm right

Then the error is pretty much expected

因为您实际上是在向该终结点发出请求,而不是将数据被动发送到该终结点或图像URL.

In Case i'm wrong

假设你做的是unit testing,这是不同的,那么你必须使用模拟数据来创建相同的行为.

Here's the example how to use multer for unit testing

Javascript相关问答推荐

Next.js Next/Image图像隐含性有任何类型-如何修复?

被CSS优先级所迷惑

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

使用i18next在React中不重新加载翻译动态数据的问题

PrivateRoute不是路由组件错误

将本机导航路由react 到导航栏中未列出的屏幕?

优化Google Sheet脚本以将下拉菜单和公式添加到多行

VUE 3捕获错误并呈现另一个组件

400 bad request error posting through node-fetch

如何将zoom 变换应用到我的d3力有向图?

为什么我的按钮没有从&q;1更改为&q;X&q;?

基于产品ID更新条带产品图像的JavaScript命中错误

使用线性插值法旋转直线以查看鼠标会导致 skip

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

在GraphQL解析器中修改上下文值

有没有办法通过使用不同数组中的值进行排序

我想为我的Reaction项目在画布上加载图像/视频,图像正在工作,但视频没有

Google OAuth 2.0库和跨域开放程序的问题-策略错误

使用导航时,路径的所有子组件都必须是路径

Html/JS:如何在脚本执行前阻止呈现?