I'm trying to mock the passport.authenticate('local'):
app.post('/login', passport.authenticate('local'), (req, res, next) => {console.log('should enter');})
Am using Sinon, but the method doesn't execute the console.log inside the login route
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();
});
});
});
Also, When I put the mock inside the real passport.authenticate('local') like this:
app.post('/login', () => {}, (req, res, next) => {console.log('should enter');})
It still doesn't enter the route which means that the sinon callFake wouldn't help at all. Only if I remove the
passport.authenticate('local')
from the /login route will the 'should login' test enter the route.
Implement sinon in beforeEach
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;
It seems you want to use a middleware callback that does nothing but just lets the request be handled by later middlewares. Such callback would be:
(req, res, next) => next()
The middleware has to call next()
for the request continue being processed by later middlewares. So you should setup your stub like this:
aut = sinon.stub(server.passport, 'authenticate').returns((req, res, next) => next());