Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

node.js - 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);
  }
});

question from:https://stackoverflow.com/questions/65891511/why-im-getting-404-instead-of-400-when-using-jest-with-mongoose

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...