【问题标题】:Cannot mock passport authenticate('local') method with sinon无法使用 sinon 模拟护照身份验证(“本地”)方法
【发布时间】:2019-06-26 05:34:14
【问题描述】:

我正在尝试模拟 passport.authenticate('local'):

 app.post('/login', passport.authenticate('local'), (req, res, next) => {console.log('should enter');})

我用的是Sinon,但是方法并没有在登录路由里面执行console.log

beforeEach(function (done) {
      aut = sinon.stub(server.passport, 'authenticate').returns(() => {});
      server.app.on('appStarted', function () {
        done();
      });
    });

afterEach(() => {
  aut.restore();
});

describe('Login', () => {
  it('should login', (done) => {
    chai.request(server.app)
      .post('/login')
      .send({
        username: 'user',
        password: 'pas'
      })
      .end(function (error, response, body) {
        return done();
      });
  });
});

另外, 当我将 模拟 放入真正的 passport.authenticate('local') 中时:

app.post('/login', () => {}, (req, res, next) => {console.log('should enter');})

它仍然没有进入路由,这意味着 sinon callFake 根本没有帮助。只有当我删除

passport.authenticate('local')

/login 路由将 'should login' 测试进入路由。

在 beforeEach 中实现 sinon

let server = require('../../../app.js');
let expect = chai.expect;
chai.use(chaiHttp);

var aut;
beforeEach(() => {
  aut = sinon.stub(server.passport, 'authenticate').returns((req, res, next) => next());
});

app.js

const app = express();

middleware.initMiddleware(app, passport);

const dbName = 'dbname';
const connectionString = 'connect string';

mongo.mongoConnect(connectionString).then(() => {
        console.log('Database connection successful');
        app.listen(5000, () => console.log('Server started on port 5000'));
    })
    .catch(err => {
        console.error('App starting error:', err.stack);
        process.exit(1);
    });

// If the Node process ends, close the Mongoose connection
process.on('SIGINT', mongo.mongoDisconnect).on('SIGTERM', mongo.mongoDisconnect);

register.initnulth(app);

login.initfirst(app, passport);
logout.initsecond(app);


module.exports = app;

【问题讨论】:

  • 你的aut存根不是异步的吗?你想要.yields 而不是.returns
  • 不确定...如何将 yield 应用到 passport.authenticate ?
  • 可以分享app.js的内容吗?
  • @eugensunic sinon.stub(server.passport, 'authenticate') 将替换server.passport 对象上的authenticate 属性,但我仍然看不到server.passport 的来源以及这是否是正确的对象为模拟。完整的代码可以在 repo 中找到吗?
  • @eugensunic 很高兴听到你成功了

标签: javascript node.js unit-testing sinon sinon-chai


【解决方案1】:

您似乎想使用一个中间件回调,它什么都不做,只是让请求由以后的中间件处理。这样的回调将是:

(req, res, next) => next()

中间件必须调用next() 才能让后续中间件继续处理请求。所以你应该像这样设置你的存根:

aut = sinon.stub(server.passport, 'authenticate').returns((req, res, next) => next());

【讨论】:

  • 看来sinon stub根本没有作用。正如我在帖子中描述的那样。 (req, res, next) => next() 是解决方案(只是在路由中实现),但我无法通过 sinon 提出任何想法。在我称之为 sinon 的地方发布了更多代码...
猜你喜欢
  • 2017-03-21
  • 2016-03-06
  • 2016-10-29
  • 2014-03-17
  • 2016-10-19
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多