Search code examples
node.jsexpressunit-testingtry-catchsinon

How to test try catch code in javascript using jest and including a next() call with middleware in express?


I am creating an API and I want to know how to test a try catch block. I want to make sure that error catch by the block is passing throw next() in express to the next middleware.

Here an example, this is my callback to POST method:

function create (req, res, next) {
  try {
    const data = {}
    response(req, res, data, 201)
  } catch (error) {
    next(error)
  }
}

I want to test that next is called. I am planing to use sinon to do it, but I want to simulate the error and verify that catching the error.

This is an screen of my coverage in jest.

enter image description here


Solution

  • If it were too much effort to reproduce an actual error, I'd just not cover that statement.

    Thanks to Jest's mock functions it's possible to spy on functions, methods and modules and temporarily replace it's implementation and return value.

    https://jestjs.io/docs/mock-function-api

    That would be something like

    // replace the implementation for your stub
    const spy = jest.spyOn(response).mockImplementation(() => { throw new Error(); });
    ...
    expect(spy).toHaveBeenCalled();
    spy.mockRestore(); // restore the implementation
    

    Mind you this syntax work for functions. If it this a method from a class, then it would be jest.spyOn(YourClass.prototype, 'methodNameInsideQuotes'). Jest is well-documented and you should get it working with no hacks.