【发布时间】: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