简体   繁体   中英

why I'm getting 404 instead of 400 when using jest with mongoose?

i want to prevent a "blog" to be submitted if it doesn't have a 'url' or a 'title'.

i have a mongoose model

const blogSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  author: String,
  url: {
    type: String,
    required: true,
  },
  likes: { type: Number, default: 0 },
});

the middleware that is responsible for handling errors

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);
};

the test goes like this

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);
  });

when using Postman i get the 400 status code (which is what i likes) but when testing with jest i get 404 instead. i don't know what i'm missing here

i don't know if you need it; but here's the post method(using express router)

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);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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