If you use Test Driven Development for your Node.js project uses Express library, you need to write unit tests among other things. As I experienced, testing code parts which use third party libraries are usually difficult for less experienced developers. The key aspect of effective unit testing is define boundaries of the business logic to be tested.
When I write unit tests including any structural items of the Express library, it produces me I have to avoid testing the library itself. It’s not my job. Rather than only my business logic needs to be tested. As for the middleware, it’s the logic inside the middleware function. The input parameters are coming from the Express library, so you need to mock or stub them.
An Express middleware is a special function which has three parameters: a request, a response and a next function. These are coming from the library flow, and you just need to wire the middleware to the proper level (application, router, etc.).
The most common problem with typescript is that a lack of knowledge of the type system that forces the programmer to try to bypass the own type system instead of taking advantage of its potential. Don’t do that! Express provides you its types for the requests (Request), responses (Response) and even for the next function (NextFunction).
#nodejs #expressjs #typescript #testing #jest