title: Correct way to unit test Express Middleware
body: <p>I have a piece of Express middleware that is set to check for a valid Content-Type header in all of my POST requests that hit my server, the code for this middleware is below:</p>
  
  <pre><code>import * as STRINGS from "../Common/strings";
  
  function ContentTypeValidator(req, res, next) {
      let contentHeader = req.get("content-type");
      if(!contentHeader) {
          res.status(400).send(STRINGS.ERROR_CONTENT_TYPE_MISSING);
      } else {
          if(contentHeader.toLowerCase() !== "application/json") {
              res.status(415).send(STRINGS.ERROR_CONTENT_TYPE_UNSUPPORTED);
          } else {
              next();
          }
      }
  }
  
  export default ContentTypeValidator;
  </code></pre>
  
  <p>I am using <code>mocha</code>, <code>chai</code> and <code>node-mocks-http</code> for my TDD and my question surrounds the tests when <code>next()</code> will not be called as <code>res.send()</code> will handle the ending of this request for me.</p>
  
  <pre><code>it("Should return 200 for valid Content-Type header", (done) =&gt; {
      req = nodeMocks.createRequest({
          headers: {
              "Content-Type": "application/json"
          }
      });
      ContentTypeValidator(req, res, (err) =&gt; {
          res.statusCode.should.equal(200);
          expect(err).to.be.undefined;
          done();
      });
  });
  
  it("Should return 400 if Content-Type header is missing", (done) =&gt; {
      ContentTypeValidator(req, res, () =&gt; {});
      res.statusCode.should.equal(400);
      res._getData().should.equal("Content-Type header missing");
      done();
  });
  </code></pre>
  
  <p>In the first test above, I am expecting this to pass, so I pass in a function to act as the <code>next()</code> function and this test passes. In the second test, I am expecting this to fail so if I pass in a function then mocah complains that the test has exceeded 2000ms as the callback function is never called, which is to be expected since <code>res.send()</code> is handling it in this instance.</p>
  
  <p>Is the way I've written the second test correct when it comes to unit testing Express middleware like this or is there a better/more advisable way to do this?</p>
  
  <p>EDIT: So just to clarify, I am focused on wanting to test the middlewear when the next callback will NOT be called, the question I'm apparently duplicating is looking at using <code>sinon</code> to check if next is called. I am looking to see how to unit test when the callback function will NOT be called.</p>