I'd like to be able to stub my middleware functions on a per-test basis. The problem, as articulated here, 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.
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) => next());
const app = require("../app.js"); // As soon as I create this, the middleware isAdmin function becomes cached and no longer mutable
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.
I'm wondering if there's a better, elegant way to work around the fact that Node caches these functions upon first require
. I was looking into maybe using proxyquire
or decache
but both seem to provide workarounds rather than sustainable solutions (although I may very well be wrong here).