节点表示es6 sinon存根中间件不起作用
问题描述:
我正在为我的Express路由器编写摩卡单元测试. 我发现无论如何我都尝试对中间件进行存根,它仍然执行中间件代码. 这是我的路由器&测试,有人能找出答案吗?
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?
路由器:
import { aMiddleware, bMiddleware, cMiddleware } from '../middleware.js';
router.post('/url', aMiddleware, bMiddleware, cMiddleware, function(req, res) { ... }
中间件:
AuthMiddleware.aMiddleware = async (req, res, next) => {
console.log('in real middleware');
next();
}
测试:
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();
}
}
终端将在中间件中显示console.log(在真正的中间件中")
terminal will show the console.log('in real middleware') in middleware
答
这可能是因为存根是在模块已经加载之后发生的.您可能需要先清除路由器文件的缓存,然后在存根后再次将其加载,因为es6将缓存导入的模块.
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.