Test your middlewares in isolation

One Paragraph Explainer

Many avoid Middleware testing because they represent a small portion of the system and require a live Express server. Both reasons are wrong — Middlewares are small but affect all or most of the requests and can be tested easily as pure functions that get {req,res} JS objects. To test a middleware function one should just invoke it and spy (using Sinon for example) on the interaction with the {req,res} objects to ensure the function performed the right action. The library node-mock-http takes it even further and factors the {req,res} objects along with spying on their behavior. For example, it can assert whether the http status that was set on the res object matches the expectation (See example below)

Code example: Testing middleware in isolation

  1. //the middleware we want to test
  2. const unitUnderTest = require("./middleware");
  3. const httpMocks = require("node-mocks-http");
  4. //Jest syntax, equivalent to describe() & it() in Mocha
  5. test("A request without authentication header, should return http status 403", () => {
  6. const request = httpMocks.createRequest({
  7. method: "GET",
  8. url: "/user/42",
  9. headers: {
  10. authentication: ""
  11. }
  12. });
  13. const response = httpMocks.createResponse();
  14. unitUnderTest(request, response);
  15. expect(response.statusCode).toBe(403);
  16. });