问题
I am writing the mocha unit test for the my express router. I found that however I try to stub the middleware, it still execute the middleware code. Here is my router & test, could anyone figure out?
Router:
import { aMiddleware, bMiddleware, cMiddleware } from '../middleware.js';
router.post('/url', aMiddleware, bMiddleware, cMiddleware, function(req, res) { ... }
Middleware:
AuthMiddleware.aMiddleware = async (req, res, next) => {
console.log('in real middleware');
next();
}
Test:
var authMiddleware = require('../../middleware/auth.js');
describe('Test', async () => {
before(function (done) {
_STUB_MIDDLEWARE_A = sinon.stub(authMiddleware, 'aMiddleware');
_STUB_MIDDLEWARE_A.callsArg(2);
}
after(function (done) {
_STUB_MIDDLEWARE_A.restore();
}
}
terminal will show the console.log('in real middleware') in middleware
回答1:
This is likely because the stub happened after the module has been loaded already. You probably need to clear the cache first for your router file and then load it in again after the stubbing because es6 will cache the imported modules.
来源:https://stackoverflow.com/questions/41392497/node-express-es6-sinon-stubbing-middleware-not-working