I've got an API built in Express, which I'm testing with Jest. The API is working just fine when I test with Postman, but when I run my test suite I usually get an ECONNABORTED error on my file uploads using .attach(). (Occasionally, it works just fine.) I'm using a suite of middleware to download an array of images referenced by URL, followed by any images passed to the endpoint via form upload. After the images are saved, I'm using a third piece of middleware to resize the images and save them in a subdirectory. Since the error only happens in Jest, it seems like that's where the error would lie, but I'm also not positive I'm handling errors with Multer correctly.
// endpoint.js
const storage = multer.diskStorage({
destination: async (req, file, cb) => {
// Check for product's existence
if (product) {
// Make the directory if necessary
cb(null, /* location */)
} else {
cb(404, null)
}
},
filename: async (req, file, cb) => {
cb(
null, /* location */}`
)
}
})
const upload = multer({ storage }).array("files")
router.post(
"/:id",
async (req, res, next) => {
// Download images from URLs if provided
next()
},
(req, res, next) => {
upload(req, res, err => {
// Handle errors (e.g. return res.status(404).json({ message: "Product not found" })
})
next()
},
async (req, res) => {
// resize and save to subdirectory
}
)
// endpoint.test.js
describe("/endpoint", () => {
describe("POST", () => {
it("saves uploaded images to the server", async () => {
const response = await request(app)
.post(`/endpoint/${id}`)
.attach("files", "assets/img-test-1.jpg")
.attach("files", "assets/img-test-2.jpg")
.set("Content-Type", "multipart/form-data")
expect(response.status).toEqual(201)
}, 30000)
...
})
Aucun commentaire:
Enregistrer un commentaire