I\'m trying to follow this example: https://www.alexjamesbrown.com/blog/development/stubbing-middleware-testing-express-supertest/ but the sinon stub doesn\'t seem to be executi
instead executes the actual authorization
This is exactly what is happening.
Note this code in server:
app.all('/api/*', authorization.authorize);
This resolves authorize
function reference in this particular state of program and express will use this particular function (original one!) for rest of program.
This:
ensureAuthenticatedSpy = sinon.stub(authorization, 'authorize');
is called later and given that sinon has no power to change references to original authorize
captured previously ... is no-op.
IOW, dependency injection in basic Javascript apps is not as simple as one might want.
To workaround, you can change original route in app.js
:
app.all('/api/*', (req, res, next) => authorization.authorize(req, res, next));
Now, your closure would resolve authorization.authorize
every-time it's called, enabling mocking/spying function you're interested in. However this is solution is far from elegant.