How to unit test middleware in Nest?
Unit test middleware in Node, Nestjs.
What is a middleware?
Middleware is a function that is called before the route handler. Middleware functions have access to the request and response objects, and the
next() middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named
The above code is an example for a middleware in nestjs. It checks for presence of header
Origin in request, if yes, it executes next function. if not, it returns
401 Unauthorised error as response.
How to approach to unit test the above middleware?
- Initialise the testing module of a nestjs application
The above code snippet helps to initialise a nest application for unit testing. After initiating the application, get handle of the middleware using the below code.
2. To test a middleware, we need to a request and response. To create a mock request and response, use `node-mocks-http` npm library ( install it as dev dependency)
3. Create a mock request and customise it according to your use case.
Need to use the mock request in multiple scenario, then please create a
beforeEach block and create the mocks in it.
4. Testing the middleware (positive scenario)
Invoke the middleware with request, response and next function. We expect the next function is called if the request has origin header. Its being tested with
5. Testing the middleware (negative scenario)
For the negative test case scenario, lets create a bad request mock (which do not have origin header), use it in middleware and expect the response to be with code
401 with Unauthorised
5. Mostly importantly, do not forget to close the app which was initiated in bootstrap
This will prevent from memory leak in unit testing.