node express es6 sinon stubbing middleware not working

﹥>﹥吖頭↗ 提交于 2019-12-19 03:36:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!