Are there any examples of unit tests with Multer ? #1196
Replies: 3 comments
|
Can you provide a minimal code you want to test? |
|
If it helps, I’d avoid mocking Multer too much and instead test the upload route with real fixture files. The useful cases are usually:
I built an OSS package around this inspect-before-storage step: Even if you don’t use it directly, that kind of fixture-driven testing tends to be much more valuable than only mocking the happy path. |
|
You usually do not need to mock Multer’s internals. Drive it through HTTP with 1) Integration-style (recommended)const request = require("supertest");
const express = require("express");
const multer = require("multer");
const upload = multer({
storage: multer.memoryStorage(),
fileFilter(req, file, cb) {
if (file.mimetype !== "image/png") return cb(null, false);
cb(null, true);
},
});
const app = express();
app.post("/upload", upload.single("file"), (req, res) => {
if (!req.file) return res.status(400).json({ error: "bad type" });
res.json({ ok: true, size: req.file.size });
});
// success
await request(app)
.post("/upload")
.attach("file", Buffer.from("fake"), { filename: "a.png", contentType: "image/png" })
.expect(200);
// rejected type
await request(app)
.post("/upload")
.attach("file", Buffer.from("fake"), { filename: "a.txt", contentType: "text/plain" })
.expect(400);2) Error pathMulter errors are often passed to 3) Avoid real diskUse That covers type validation, happy path, and system/limit errors without deep mocks. |
Uh oh!
There was an error while loading. Please reload this page.
Hi everyone,
I've just finished adding Multer to my project, however, now I've got write some unit tests.
Is there any easy way to mock how Multer work's without adding a bunch of complexity ?
I want to be able to test the following:
All reactions