节点表示es6 sinon存根中间件不起作用 [英] node express es6 sinon stubbing middleware not working

查看:118
本文介绍了节点表示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.

这篇关于节点表示es6 sinon存根中间件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆