'How to catch mongoose DB calls in Jest?

Here's my service:

  create: async (user: User): Promise<User> => {
    try {
      return await UserModel.create(user);
    } catch (err) {
      console.log("error: ", err);
      throw err;
    }
  },

I'm using Jest to perform integration tests and test coverage wants me to test what happens if the catch statement kicks in so we get 100% coverage ...

... but how!

This is my approach so far:

test("Does the catch block fire", async () => { const mock = jest .spyOn(userModel, "find") .mockImplementation(() => { throw "faked error"; });

expect(async () => {
  await userModel.getAll(); //this is where userModel.find() gets called
}).toThrow();

mock.mockRestore();

});

But the error I'm getting is 'received function did not throw.

And btw, mock.mockRestore() isn't working for later tests as it still throws 'fake error'.

What am I doing wrong!!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source