【发布时间】:2019-07-22 23:42:31
【问题描述】:
我有一个内置在 Express 中的 API,我正在使用 Jest 对其进行测试。当我使用 Postman 进行测试时,API 工作得很好,但是当我运行我的测试套件时,我通常在使用 .attach() 上传文件时收到 ECONNABORTED 错误。 (有时,它工作得很好。)我正在使用一套中间件来下载一组由 URL 引用的图像,然后是通过表单上传传递给端点的任何图像。保存图像后,我使用第三个中间件来调整图像大小并将它们保存在子目录中。由于错误仅发生在 Jest 中,因此错误似乎就在于此,但我也不肯定我正在正确处理 Multer 的错误。
// 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)
...
})
编辑:通过将 next() 调用移动到 Multer 处理程序中修复了原始错误。但是,现在发生了相同的错误,只是在不同的测试中。同样,该错误仅在由测试脚本运行时发生;通过 Postman 拨打相同的电话时,我没有遇到任何问题。
// endpoint.js
let errors
router.post(
"/:id",
async (req, res, next) => {
errors = []
...
// This is the problematic call. If I explicitly set
// product = null, the test runs normally
const product = await Product.findById(req.params.id)
if (!product) {
errors.push({ status: 404, message: "Product not found" })
return next()
}
...
return next()
},
// Several more middleware functions
})
// endpoint.test.js
...
beforeAll(done => {
app.on("ready", async () => {
const newProduct = await Product.create(product)
id = newProduct._id
done()
})
})
...
describe("/api/bam/images", () => {
describe("POST", () => {
...
it("returns a 404 error if the associated product is not found", async () => {
const response = await request(app)
.post("/api/bam/images/000000000000000000000000")
.attach("files", "assets/img-test-1.jpg")
.attach("files", "assets/img-test-2.jpg")
expect(response.status).toEqual(404)
})
})
})
【问题讨论】:
标签: node.js express mongoose jestjs multer