How to test a catch clause if I can't reproduce the error during the test? How to test a catch clause if I can't reproduce the error during the test? mongoose mongoose

How to test a catch clause if I can't reproduce the error during the test?


In unit-test your should test only your code and should not rely on 3rd party libraries. Of course, this advice should be applied reasonably (e.g. we must depend on the compiler and out-of-box libraries of the platform we are using).

Up to now it seemed reasonable not to stub json as it's a quite established library you can rely on. But as soon as you want test such behavior as thrown exceptions there is no other way than create a stub, inject it somehow into your code, and in test setup make it throw an exception when calling json.

As a side effect, this will decouple your code from a particular implementation of json and make your code more flexible. Of course decoupling from JSON implementations seems a bit over the top, but nevertheless shows how test-driven design works in this case (even though the code was first).