title: How to unit test a chain of express middlewares?
body: <p>I have a controller class that exports an array containing a number of middlewares (utilizing <a href="https://github.com/express-validator/express-validator" rel="nofollow noreferrer">express-validator</a>) that verify that all essential parts of a request are present and as the last element of the array the handler for the request:</p>
  
  <p><strong>Controller class:</strong></p>
  
  <pre class="lang-js prettyprint-override"><code>import { body, ValidationChain } from "express-validator/check";
  import { Request, Response, Handler } from "express";
  
  export default class UserController {
      signupChainPost: Handler[];
  
      constructor() {
  
          this.signupChainPost = [
              this.getEmailExistsMiddleware("email"),
              this.getPasswordValidationMiddleware("password"),
              this.signupHandlerPost.bind(this)
          ];
      }
  
      private getEmailExistsMiddleware(fieldName: string): ValidationChain {
          return body(fieldName, "some error").isEmail().custom((value, { req }) =&gt; {
              // ...
          });
      }
  
      private getPasswordValidationMiddleware(fieldName: string): ValidationChain {
          return body(fieldName, "some error").isLength({ min: 5 });
      }
  
      private async signupHandlerPost(req: Request, res: Response) {
          // request handling
      }
  }
  </code></pre>
  
  <p><strong>Usage of the controller class in the main server file using Epxress.js:</strong></p>
  
  <pre class="lang-js prettyprint-override"><code>const userController = new UserController();
  app.post("/user/create", userController.signupChainPost);
  </code></pre>
  
  <p>Now I want to write unit tests for my request handler but I can't figure out how to test an array of middlewares/handlers. Should I only test the "real handler" and trust the middlewares to prevent invalid requests from reaching my handler? Or is my application design fundamentally wrong which leads to the unit tests being hard to write?</p>
  
  <p>Thanks in advance for the help :)</p>