-1

Situation
I am building and testing a simple api with express. One of the routes is /api/blogs/:id, where the api should return a status 400 if the provided id is in the wrong format, and 404 if the id is not present in the database.

Problem
The api works fine and responds with the right status codes when making requests by browser or the REST client plugin in vsCode. But when I make requests with a malformed id via Superagent in my unit tests, the server responds with a 404, when it should be a 400.

Jest error message saying it expected status 400 but got status 404

Route

blogsRouter.get('/:id', async (req, res, next) => {
  try {
    const { id } = req.params;
    const blog = await Blog.findById(id);
    if (blog) {
      res.status(200).json(blog);
    } else {
      res.status(404).end();
    }
  } catch (error) {
    next(error);
  }
});

Normally, Mongoose throws an error when running Blog.findById(id), triggering catch (error) { next(error) }, which executes the next middleware function errorHandler. For some reason though, this doesn't seem to happen when testing.

errorHandler

const errorHandler = (error, req, res, next) => {
  if (error.name === 'CastError') {
    res.status(400).json({ error: 'malformatted id' });
    return;
  } if (error.name === 'ValidationError') {
    console.log(error.message);
    res.status(400).json({ error: error.message });
    return;
  }

  next(error);
};

test

test("fails with status 400 when 'id' has wrong format", async () => {
  const invalidId = '45234sdsdasf';
  await api.get(`/api/blogs/${invalidId}`)
    .expect(400);
});
Osocman
  • 81
  • 8

1 Answers1

0

I found the solution.

The problem was const invalidId = '45234sdsdasf'.

This should be a malformed id, but for some reason Mongoose sees 12 characters long strings as a correct objectId. Changing invalidId to something else solved the problem.

Osocman
  • 81
  • 8