title: Simple way to test middleware in Express without creating recreating server?
body: <p>I'd like to be able to stub my middleware functions on a per-test basis. The problem, as articulated <a href="https://stackoverflow.com/a/53857460/3813411">here</a>, is that I can't just stub my middleware functions since node has cached the middleware function so I can't stub it since I create my app at the very beginning.</p>
  
  <pre><code>const request = require("supertest");
  const { expect } = require("chai");
  const sinon = require('sinon');
  const auth = require ("../utils/auth-middleware")
  const adminStub = sinon.stub(auth, "isAdmin").callsFake((req, res, next) =&gt; next());
  const app = require("../app.js"); // As soon as I create this, the middleware isAdmin function becomes cached and no longer mutable
  </code></pre>
  
  <p>The above works as the solution described in the linked SO answer, but I don't like that in order to restore the stub or modify the fake, I have to completely recreate the server.</p>
  
  <p>I'm wondering if there's a better, elegant way to work around the fact that Node caches these functions upon first <code>require</code>. I was looking into maybe using <code>proxyquire</code> or <code>decache</code> but both seem to provide workarounds rather than sustainable solutions (although I may very well be wrong here).</p>