Why is my sinon stub acting like it's calling the real function?

后端 未结 1 965
攒了一身酷
攒了一身酷 2021-01-28 04:40

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

相关标签:
1条回答
  • 2021-01-28 05:40

    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.

    0 讨论(0)
提交回复
热议问题