Search code examples
javascripttypescriptexpressjestjsmulter

Multer is undefined in express app while testing with Jest


I am using jest to test my express app made with TS which uses multer to upload files. But my test ends with error "TypeError: Cannot read properties of undefined (reading 'diskStorage')". The app works fine, the error is only when I test.

My error happens in -

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;

Then I am using it in my routes -

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;

My jest code is -

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

I would really appreciate any help. Thank you.


Solution

  • What you doing here is basically the integration testing which means that you've actually making the request and actually storing the data in db right ??

    In Case i'm right

    Then the error is pretty much expected

    because you're actually making the request to that endpoint,but aren't passig the data to that endPoint or the image url if you wanna say.

    In Case i'm wrong

    let's say you're doing the unit testing which's differet then you'd have to use the mock data to create the same behaviour.

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