繁体   English   中英

为什么我在与 mongoose 一起使用 jest 时得到 404 而不是 400?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM