
[英]I am getting internal error 500 instead of 404 in mongoose when using res.json()
[英]why I'm getting 404 instead of 400 when using jest with mongoose?
如果没有“url”或“标题”,我想阻止提交“博客”。
我有一个 mongoose model
const blogSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
author: String,
url: {
type: String,
required: true,
},
likes: { type: Number, default: 0 },
});
负责处理错误的中间件
const errorHandler = (error, request, response, next) => {
logger.error(error.message);
if (error.name === "CastError") {
return response.status(400).send({ error: "malformatted id" });
} else if (error.name === "ValidationError") {
return response.status(400).json({ error: error.message });
}
next(error);
};
测试是这样的
test("you can not add a post wihout a title or url", async () => {
const blog = {
author: "Chris Coyier",
likes: 56,
};
const res = await api.post("/api/blog").send(blog);
expect(res.status).toBe(400);
});
当使用 Postman 时,我得到 400 状态码(这是我喜欢的),但是当用jest
进行测试时,我得到 404。 我不知道我在这里缺少什么
我不知道你是否需要它; 但这是 post 方法(使用快速路由器)
blogsRouter.post("/", async (req, res, next) => {
const blog = new Blog(req.body);
try {
const result = await blog.save();
res.status(200).json(result);
} catch (err) {
next(err);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.