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.

Test the business logic, and nothing else

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.

Mock or stub only the needed parts coming from Express, nothing more

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.).

Stay typed (use official Express types)

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

How to Unit Test Express Middleware
47.50 GEEK