我有一个内置于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处理程序,已解决了原始错误。但是,现在发生相同的错误,只是在不同的测试上。同样,该错误仅在通过测试脚本运行时才会发生。通过邮递员拨打相同的电话时,我没有任何问题。
// 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)
})
})
})
答案 0 :(得分:0)
我认为问题可能与在完成multer上传之前调用.as-console-wrapper { max-height: 100% !important; top: 0; }
有关-尝试在上传回调中移至下一个:
next()
PT2:与编辑有关,如果问题似乎与(req, res, next) => {
upload(req, res, err => {
// Handle errors (e.g. return res.status(404).json({ message: "Product not found"
next()
})
})
},
调用有关,则可能引发了一个错误而没有捕获该错误-当您等待被拒绝的诺言时,它的行为就像正常的抛出。扔到这里意味着await
永远不会被呼叫:
next