An Approach to Testing Middleware
I’ve always tested middleware in one of two ways, a unit test with mocks and asserting the callback in the
handle method or integration tests on application routes.
The problem with unit testing is that you don’t have any visibility into if the middleware is actually active and you also don’t know how it will function as the request is passed through other active middleware.
Using integration tests on application routes resolves some of the issues with unit testing middleware but it makes it a little bit harder to make assertions on how the middleware is actually functioning. I also found myself wanting to constantly verify that the middleware was active and working on each of my application routes.
Testing the Middleware
I wanted to find a simple approach that verified the following:
- Middleware is active, and configured correctly (global, group, single use)
- Middleware is functioning correctly
Lets take a look at some examples
So what I’ve done here is define custom testing routes and applied the middleware as I would use it in the application routes, in this case global middleware and as middleware for the
api group. This allows me to assert that the middleware is configured and functioning correctly.
The only potential drawback to this approach is that it still relies on the developer to ensure the application routes are assigned middleware correctly. This could still be mitigated by testing what middleware is active on each route. This isn’t something I typically worry about though.